这是场景。
用户从表单上载一个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文件上传到Google云存储的正确方法是什么
答案 0 :(得分:0)
根据@Valkyrie提供的评论,将其发布为Community Wiki答案,并告知她为解决该问题所做的工作。
解决方案是将fileInptStream
转换为byteArray
,然后将byteArray
转换为byteArrayInputStream
,如下所示:
byte[] data = IOUtils.toByteArray(filePartInputStream)
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)
通过这种方式,将文件上传到Cloud Storage后,一旦下载,文件就不会损坏。