[英]Uploading a zip folder to cloud storage
Here's the scenario.这是场景。
User uploads a zip file from a form.用户从表单上传 zip 文件。 On the backend, I get the ZipInputStream and convert the inputstream to bytes and upload to GCS
在后端,我得到 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);
}`
COde that gets the filepart and calls the above method获取文件部分并调用上述方法的代码
ZipInputStream filePartInputStream = new ZipInputStream(filePart.getInputStream());
storageGateway.uploadObject(
"bucket_name",
"objectname",
filePart.getContentType(),
filePartInputStream
);
The upload works as expected but when I download the zip folder from GCS bucket, it seems to be corrupted.上传按预期工作,但是当我从 GCS 存储桶下载 zip 文件夹时,它似乎已损坏。 I was not able to unzip it.
我无法解压缩它。
Am I missing anyhting here?我在这里想念什么吗? If not what's the correct way to upload a zip file to google cloud storage
如果不是将 zip 文件上传到谷歌云存储的正确方法是什么
Posting this as Community Wiki answer, based in the comment provided by @Valkyrie, informing what she did to fix it.根据@Valkyrie 提供的评论,将此作为社区 Wiki 答案发布,告知她为修复它所做的工作。
The solution is to convert the fileInptStream
to a byteArray
and then, convert the byteArray
to a byteArrayInputStream
as below:解决方案是将
fileInptStream
转换为byteArray
,然后将byteArray
转换为byteArrayInputStream
,如下所示:
byte[] data = IOUtils.toByteArray(filePartInputStream)
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)
This way, once the file is downloaded after being uploaded to Cloud Storage, the file should not be corrupted.这样,一旦文件上传到云存储后下载,文件就不会损坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.