我正在尝试将图片上传到Google Cloud 端存储中的现有存储分区 . 当我去检查时,图像文件成功上传,
但是返回的下载网址是 null
代码
private String uploadImage(File filePath, String blobName, File uploadCreds) throws FileNotFoundException, IOException{
Storage storage = StorageOptions.newBuilder().setProjectId("myProjectId")
.setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(uploadCreds)))
.build()
.getService();
String bucketName = "myBucketName";
Bucket bucket = storage.get(bucketName);
BlobId blobId = BlobId.of(bucket.getName(), blobName);
InputStream inputStream = new FileInputStream(filePath);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();
try (WriteChannel writer = storage.writer(blobInfo)) {
byte[] buffer = new byte[1024];
int limit;
try {
while ((limit = inputStream.read(buffer)) >= 0) {
writer.write(ByteBuffer.wrap(buffer, 0, limit));
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
writer.close();
}
System.out.println("Image URL : " + blobInfo.getMediaLink());
System.out.println("Blob URL : " + blobInfo.getSelfLink());
return blobInfo.getMediaLink();
}
}
filePath是图像文件
blobName是一个随机图像名称
uploadCreds是我的credintials.json文件
为什么 blobInfo.getMediaLink()
和 blobInfo.getSelfLink()
返回 null
?
我究竟做错了什么?
2 回答
这是我的代码完美无缺
@RestController @RequestMapping(“/ api”)公共类CloudStorageHelper {
答案非常简单,我只是摆脱了手动上传方法并使用了内置的创建blob .