【问题标题】:Uploading a zip folder to cloud storage将 zip 文件夹上传到云存储
【发布时间】: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。我不记得ZipInputStream API,但您当前的解决方案可能实际上是在即时解压缩zip,而您正在将非压缩文件写入存储。
  • 注意:zip 文件的content-encodingapplication/zip 而不是gzip
  • @Valkyrie 上传后,你是否可以使用gsutil cp 下载文件,并像你最初上传的那样得到一个完整的压缩文件?这将告诉您上传成功,并且您的下载路径有问题。

标签: file-upload google-cloud-platform google-cloud-storage zipfile


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 2017-12-21
    • 2020-03-16
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多