我该如何在Google Cloud Storage Bucket中解压.zip文件?(如果我们有其他工具,如AWS的“CloudBerry Explorer”,那就太好了。)
我该如何在Google Cloud Storage Bucket中解压.zip文件?(如果我们有其他工具,如AWS的“CloudBerry Explorer”,那就太好了。)
您可以使用Python,例如从云函数中:
from google.cloud import storage
from zipfile import ZipFile
from zipfile import is_zipfile
import io
def zipextract(bucketname, zipfilename_with_path):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucketname)
destination_blob_pathname = zipfilename_with_path
blob = bucket.blob(destination_blob_pathname)
zipbytes = io.BytesIO(blob.download_as_string())
if is_zipfile(zipbytes):
with ZipFile(zipbytes, 'r') as myzip:
for contentfilename in myzip.namelist():
contentfile = myzip.read(contentfilename)
blob = bucket.blob(zipfilename_with_path + "/" + contentfilename)
blob.upload_from_string(contentfile)
zipextract("mybucket", "path/file.zip") # if the file is gs://mybucket/path/file.zip
这是我创建的一些代码,可作为Firebase云函数运行。 它旨在监听加载到具有content-type 'application/zip'的存储桶中的文件,并将其原地提取。
const functions = require('firebase-functions');
const admin = require("firebase-admin");
const path = require('path');
const fs = require('fs');
const os = require('os');
const unzip = require('unzipper')
admin.initializeApp();
const storage = admin.storage();
const runtimeOpts = {
timeoutSeconds: 540,
memory: '2GB'
}
exports.unzip = functions.runWith(runtimeOpts).storage.object().onFinalize((object) => {
return new Promise((resolve, reject) => {
//console.log(object)
if (object.contentType !== 'application/zip') {
reject();
} else {
const bucket = firebase.storage.bucket(object.bucket)
const remoteFile = bucket.file(object.name)
const remoteDir = object.name.replace('.zip', '')
console.log(`Downloading ${remoteFile}`)
remoteFile.createReadStream()
.on('error', err => {
console.error(err)
reject(err);
})
.on('response', response => {
// Server connected and responded with the specified status and headers.
//console.log(response)
})
.on('end', () => {
// The file is fully downloaded.
console.log("Finished downloading.")
resolve();
})
.pipe(unzip.Parse())
.on('entry', entry => {
const file = bucket.file(`${remoteDir}/${entry.path}`)
entry.pipe(file.createWriteStream())
.on('error', err => {
console.log(err)
reject(err);
})
.on('finish', () => {
console.log(`Finsihed extracting ${remoteDir}/${entry.path}`)
});
entry.autodrain();
});
}
})
});
如果你因为使用gsutil cp
命令从另一台服务器移动大文件而在Google Cloud Storage存储桶上有一个zip文件,你可以在复制时对其进行gzip压缩,这样它就会以压缩格式传输并在到达存储桶时进行解压。
可以通过使用-Z参数在gsutil cp中内置实现此功能。
例如:
gsutil cp -Z largefile.txt gs://bucket/largefile.txt
gsutil cp -Z
并不能做到这一点。它会将文件压缩并保留在存储桶中。来源:https://cloud.google.com/storage/docs/gsutil/commands/cp#synchronizing-over-os-specific-file-types-such-as-symlinks-and-devices - uriggsutil cat gs://bucket/obj.csv.gz | zcat | gsutil cp - gs://bucket/obj.csv
gsutil cat gs://bucket/obj.zip | jar xvf /dev/stdin
- Dishant Mishragsutil cat gs://bucket/*/*/*/*.gz | zcat | gsutil cp - gs://bucket/decompressed/result.json
- Abdurrahman I.Google Cloud Dataflow有数据流模板,可以帮助在云存储中压缩/解压文件。请参考下面的截屏。
该模板实现了一个批处理管道,将Cloud Storage上的压缩文件解压到指定位置。当您想要使用压缩数据以最小化网络带宽成本时,此功能非常有用。 在单个执行期间,管道会自动处理多种压缩模式,并根据文件扩展名(.bzip2、.deflate、.gz、.zip)确定要使用的解压缩模式。
管道要求
要解压缩的文件必须是以下格式之一:Bzip2、Deflate、Gzip、Zip。
在管道执行之前,输出目录必须存在。
temp
目录(不能使用根目录)。YOUR_REGION
(例如europe-west6
)和YOUR_BUCKET
,然后使用gcloud cli运行该命令(假设gz
文件位于根目录 - 如果不是,请更改):gcloud dataflow jobs run unzip \
--gcs-location gs://dataflow-templates-YOUR_REGION/latest/Bulk_Decompress_GCS_Files \
--region YOUR_REGION \
--num-workers 1 \
--staging-location gs://YOUR_BUCKET/temp \
--parameters inputFilePattern=gs://YOUR_BUCKET/*.gz,outputDirectory=gs://YOUR_BUCKET/,outputFailureFile=gs://YOUR_BUCKET/decomperror.txt
很抱歉,在Google Cloud中默认情况下,没有任何程序可以实现这个功能...但是你可以通过使用Python等工具来实现。
您需要输入以下命令:
python
或者如果您需要管理员权限:
sudo python
然后在 Python 解释器 中:
>>> from zipfile import ZipFile
>>> zip_file = ZipFile('path_to_file/t.zip', 'r')
>>> zip_file.extractall('path_to_extract_folder')
最后,按下Ctrl+D退出Python解释器。
解压后的文件将位于您指定的位置(当然,如果您有这些位置的适当权限)。
以上方法在Python 2和Python 3中均可使用。
尽情享受吧!:)
您可以使用Cloud Storage触发器创建Google Cloud Function。
当新对象被创建时,该函数将被触发。
const functions = require("@google-cloud/functions-framework");
const {Storage} = require("@google-cloud/storage");
const unzip = require("unzip-stream");
functions.cloudEvent("gcs-unzip", async cloudEvent => {
//console.log(JSON.stringify(cloudEvent, null, 4));
const zipFile = cloudEvent.data;
//console.log(JSON.stringify(file, null, 4));
if (zipFile.contentType === "application/zip") {
const storage = new Storage();
async function unzipAndUploadContainedFiles() {
await storage
.bucket(zipFile.bucket)
.file(zipFile.name)
.createReadStream()
.pipe(unzip.Parse())
.on("entry", async function (entry) { //there could be multiple files and even a directory structure in the zip file
//console.log(JSON.stringify(entry, null, 4));
const gcsTargetFileName = zipFile.name.replace(".zip", "") + "/" + entry.path;
if (entry.type === "File") {
entry.pipe(storage.bucket(zipFile.bucket).file(gcsTargetFileName).createWriteStream());
}
});
}
await unzipAndUploadContainedFiles().catch(err => {
console.error(err);
});
} else {
console.log("Non-zip file ignored.");
}
});
另一个快速的方法是使用版本3.2或更高版本的Python:
import shutil
shutil.unpack_archive('filename')
shutil.unpack_archive('filename', 'extract_dir')
shutil
模块的文档:shutil.unpack_archive