繁体   English   中英

将 zip 文件夹上传到云存储

[英]Uploading a zip folder to cloud storage

这是场景。

用户从表单上传 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 文件上传到谷歌云存储的正确方法是什么

根据@Valkyrie 提供的评论,将此作为社区 Wiki 答案发布,告知她为修复它所做的工作。

解决方案是将fileInptStream转换为byteArray ,然后将byteArray转换为byteArrayInputStream ,如下所示:

byte[] data = IOUtils.toByteArray(filePartInputStream) 
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)

这样,一旦文件上传到云存储后下载,文件就不会损坏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM