java - 无法使用 Spring Boot 在 Firebase 存储上预览上传的图像
问题描述
我正在尝试使用spring boot在firebase存储中上传文件,下面是我的一段代码,我的文件正在上传,但我尝试从firebase UI预览它是预览没有加载(请参考图片)
,而当我从firebase UI的上传文件选项上传相同的文件时,它正在预览。请帮助我解决这个问题。
public FileRequest uploadImage(FileRequest fileRequest, MultipartFile file) throws IOException {
if(file.isEmpty()){
throw new NullPointerException("No File Found..");
}
byte[] fileByteArray = file.getBytes();
ClassPathResource resource = new ClassPathResource("firebase.json");
Storage storage = StorageOptions
.newBuilder()
.setCredentials(ServiceAccountCredentials
.fromStream(resource.getInputStream()))
.build()
.getService();
BlobId blobId = BlobId.of(FileConstant.bucketName,fileRequest.getUploadContext() + "/" + fileRequest.getFileId());
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(fileRequest.getMimeType()).build();
storage.create(blobInfo,fileByteArray);
return fileDAO.uploadFile(fileRequest);
}
解决方案
当您通过 firebase UI 上传文件时,会自动生成访问令牌,但不会为通过 Java 上传的文件生成访问令牌。
您需要创建一个 Map 来定义一些元数据。
Map<String, String> map = new HashMap<>();
map.put("firebaseStorageDownloadTokens", imageName);
并将其传递到您的 blobInfo 中:
BlobInfo blobInfo = BlobInfo.newBuilder(blobId)
.setMetadata(map)
.setContentType(file.getContentType())
.build();
您的代码应如下所示:
public FileRequest uploadImage(FileRequest fileRequest, MultipartFile file) throws IOException {
if(file.isEmpty()){
throw new NullPointerException("No File Found..");
}
byte[] fileByteArray = file.getBytes();
ClassPathResource resource = new ClassPathResource("firebase.json");
Storage storage = StorageOptions
.newBuilder()
.setCredentials(ServiceAccountCredentials
.fromStream(resource.getInputStream()))
.build()
.getService();
String imageName = fileRequest.getUploadContext() + "/" + fileRequest.getFileId();
Map<String, String> map = new HashMap<>();
map.put("firebaseStorageDownloadTokens", imageName);
BlobId blobId = BlobId.of(FileConstant.bucketName, imageName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setMetadata(map).setContentType(fileRequest.getMimeType()).build();
storage.create(blobInfo,fileByteArray);
return fileDAO.uploadFile(fileRequest);
}
推荐阅读
- arrays - 检查数组中值的特定组合
- php - IF 语句失败
- python - Pandas groupby 计算百分比变化列
- c# - 使用 C# 和 Microsoft.TeamFoundationServer.Client 将代码签入到 TFS 2017
- vba - fillseries vba excel
- java - 访问 Hashmap 但导致 NullPointerException
- php - MySQL:快速字数统计
- javascript - 为什么 onclick() 在按钮标签内不起作用?
- javascript - AutoFocus TinyMCE Editor TextArea inside Bootstrap Modal 显示 Modal 时
- sql - SQL - 从“选择返回的多行”中收集值