如何使用带有WriteChannel和MD5检查的JAVA库上传到Google Storage



使用写入写入程序通道的输出流时,如何对上载的内容执行MD5检查?当我执行Storage::create时,所提供的BlobInfo中的MD5会被EMPTY_BYTE_ARRAY_MD5覆盖。这是有道理的,因为当blob最初创建时,它确实是空的。但我希望编写器上有一些方法可以设置一个更新的MD5,该MD5在编写器关闭后应该是有效的。我找不到实现这一目标的方法,有可能吗?我会附上我的代码:

等级:

api 'com.google.cloud:google-cloud-storage:1.51.0'

Java代码:

import com.google.cloud.WriteChannel;
import com.google.cloud.storage.*;
import com.google.common.io.ByteStreams;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.file.Path;
class StorageServiceImpl {
@Inject
private Storage storage;
public BlobInfo uploadFile(final Path localFile, final String bucketName, final String fileName, final String downloadFileName) throws IOException {
Blob blob = null;
String checksum = md5(localFile);
try (InputStream inputStream = new FileInputStream(localFile.toFile())) {
blob = storage.create(
BlobInfo.newBuilder(bucketName, fileName)
.setContentType("application/octet-stream")
.setContentDisposition(String.format("attachment; filename="%s"", downloadFileName))
.setMd5(checksum)
.build()
);
try (WriteChannel writer = blob.writer(Storage.BlobWriteOption.md5Match())) {
ByteStreams.copy(inputStream, Channels.newOutputStream(writer));
}
} catch (StorageException ex) {
if (!(400 == ex.getCode() && "invalid".equals(ex.getReason()))) {
throw ex;
}
}
return blob;
}
}

一旦我们从不推荐使用的方法Blob create(BlobInfo blobInfo, InputStream content, BlobWriteOption... options);迁移过来,就会出现这个问题。

谷歌云支持的答案

不要创建blob并向blob请求写入程序。相反,向存储器请求一个写入程序,并向该请求提供blob信息。

import com.google.cloud.WriteChannel;
import com.google.cloud.storage.*;
import com.google.common.io.ByteStreams;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.file.Path;
class StorageServiceImpl {
@Inject
private Storage storage;
public BlobInfo uploadFile(final Path localFile, final String bucketName, final String fileName, final String downloadFileName) throws IOException {
BlobInfo blobInfo = null;
String checksum = md5(localFile);
try (InputStream inputStream = new FileInputStream(localFile.toFile())) {
blobInfo =
BlobInfo.newBuilder(bucketName, fileName)
.setContentType("application/octet-stream")
.setContentDisposition(String.format("attachment; filename="%s"", downloadFileName))
.setMd5(checksum)
.build();
try (WriteChannel writer = storage.writer(blobInfo, Storage.BlobWriteOption.md5Match())) {
ByteStreams.copy(inputStream, Channels.newOutputStream(writer));
}
} catch (StorageException ex) {
if (!(400 == ex.getCode() && "invalid".equals(ex.getReason()))) {
throw ex;
}
}
return blobInfo;
}
}

最新更新