【发布时间】:2020-07-30 16:19:22
【问题描述】:
这是场景。
用户从表单上传 zip 文件。在后端,我获取 ZipInputStream 并将输入流转换为字节并上传到 GCS
`public String upload(
String bucketName,
String objectName,
String contentType,
InputStream objectInputStream)
throws IOException {
if (contentType == null) contentType = ContentType.CONTENT_TYPE_TEXT_PLAIN_UTF8;
BlobId blobId;
if (largeFile) {
blobId = BlobId.of(bucketName, objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(contentType).build();
WriteChannel writer = storage.writer(blobInfo);
if (storage.get(blobId) != null) writer = storage.update(blobInfo).writer();
byte[] buffer = new byte[1024];
int limit;
while ((limit = objectInputStream.read(buffer)) >= 0) {
try {
writer.write(ByteBuffer.wrap(buffer, 0, limit));
} catch (Exception e) {
logger.error("Exception uploadObject", e);
}
}
writer.close();
} else {
byte[] objectBytes = ByteStreams.toByteArray(objectInputStream);
blobId = storeByteArray(storage, bucketName, objectName, contentType, objectBytes);
if (Objects.isNull(blobId)) return null;
}
return url(bucketName, objectName);
}`
获取文件部分并调用上述方法的代码
ZipInputStream filePartInputStream = new ZipInputStream(filePart.getInputStream());
storageGateway.uploadObject(
"bucket_name",
"objectname",
filePart.getContentType(),
filePartInputStream
);
上传按预期工作,但是当我从 GCS 存储桶下载 zip 文件夹时,它似乎已损坏。我无法解压缩它。
我在这里错过了什么吗?如果不是,将 zip 文件上传到谷歌云存储的正确方法是什么
【问题讨论】:
-
上传对象的内容编码设置是什么?我见过的一种情况是客户端或库(或浏览器)基于此标头自动解码。并且(假设您在本地 Linux 机器上运行)运行
file downloaded_file的输出是什么? -
@MikeSchwartz 我在上传文件时将 blob 的 contentEncoding 设置为“gzip”。但结果是一样的。在本地,我在 MAC 上运行它。编辑:我运行了命令文件 file_name.zip。输出为 file_name.zip: empty
-
如果您不打算即时解压,则无需使用
ZipInputStream,只需将filePart.getInputStream传递给storageGateway。我不记得ZipInputStreamAPI,但您当前的解决方案可能实际上是在即时解压缩zip,而您正在将非压缩文件写入存储。 -
注意:zip 文件的
content-encoding是application/zip而不是gzip。 -
@Valkyrie 上传后,你是否可以使用
gsutil cp下载文件,并像你最初上传的那样得到一个完整的压缩文件?这将告诉您上传成功,并且您的下载路径有问题。
标签: file-upload google-cloud-platform google-cloud-storage zipfile