代码之家  ›  专栏  ›  技术社区  ›  codebot

如何将大文件上传到gcp云存储?

  •  1
  • codebot  · 技术社区  · 7 年前

    我有3GB大小的数据文件要上传到GCP云存储中。我尝试了gcp上传对象教程中的示例。但当我试图上传时,我得到了以下错误。

    java.lang.OutOfMemoryError: Required array size too large
    

    我试着这样做,

    BlobId blobId = BlobId.of(gcpBucketName, "ft/"+file.getName());
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
    Blob blob = storage.get().create(blobInfo, Files.readAllBytes(Paths.get(file.getAbsolutePath())));
    return blob.exists();
    

    我该怎么解决?有没有可能使用GCP云存储Java客户端上传大文件?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Alexey Alexeenka    7 年前

    存储版本:

      <artifactId>google-cloud-storage</artifactId>
      <version>1.63.0</version>
    

    制备:

                BlobId blobId = BlobId.of(BUCKET_NAME, date.format(BASIC_ISO_DATE) + "/" + prefix + "/" + file.getName());
                BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("application/gzip").build();
                uploadToStorage(storage, file, blobInfo);
    

    主要方法:

    private void uploadToStorage(Storage storage, File uploadFrom, BlobInfo blobInfo) throws IOException {
        // For small files:
        if (uploadFrom.length() < 1_000_000) {
            byte[] bytes = Files.readAllBytes(uploadFrom.toPath());
            storage.create(blobInfo, bytes);
            return;
        }
    
        // For big files:
        // When content is not available or large (1MB or more) it is recommended to write it in chunks via the blob's channel writer.
        try (WriteChannel writer = storage.writer(blobInfo)) {
    
            byte[] buffer = new byte[10_240];
            try (InputStream input = Files.newInputStream(uploadFrom.toPath())) {
                int limit;
                while ((limit = input.read(buffer)) >= 0) {
                    writer.write(ByteBuffer.wrap(buffer, 0, limit));
                }
            }
    
        }
    }
    
        2
  •  1
  •   mgoya    7 年前

    这是因为 文件.readAllBytes 有一个 bigger size than the maximum allowed .

    解决方法是将文件分成多个字节数组,将它们作为单独的文件上载到bucket中,并使用 gsutil compose command .