Spring Boot REST接口上传图片到Google Cloud Storage为空问题求助
问题根因
你调用GCS SDK的storage.create()方法时,只传入了BlobInfo对象定义了文件的存储桶和文件名,没有传入需要上传的文件内容,所以GCS只会创建一个空的同名文件,大小自然为0字节。
你代码里把MultipartFile转成本地convFile的步骤完全没用上,属于冗余代码,可以直接删掉,也不需要在本地落盘,直接用文件流/字节数组上传即可。
修复代码
直接修改ReviewService类的saveReview方法中GCS上传逻辑即可:
public String saveReview(Review review, MultipartFile file) throws ExecutionException, InterruptedException, IOException { // 先做非空校验,避免空指针 if (file == null || file.isEmpty()) { throw new IllegalArgumentException("上传文件不能为空"); } // 不需要转本地文件,直接拿字节数组上传即可,省掉本地IO步骤 BlobInfo blobInfo = storage.create( BlobInfo.newBuilder(BUCKET_NAME, file.getOriginalFilename()).build(), file.getBytes() // 这里传入文件内容,之前你漏了这个参数 ); System.out.println(blobInfo.getMediaLink()); // 下面的Firestore逻辑保持不变即可 Firestore dbFirestore= FirestoreClient.getFirestore(); ApiFuture<WriteResult> collectionApiFuture=dbFirestore.collection(COLLECTION_NAME).document(review.getName()).set(review); return collectionApiFuture.get().getUpdateTime().toString(); }
如果上传的文件比较大,推荐用流的方式上传,内存占用更低:
BlobInfo blobInfo = storage.create( BlobInfo.newBuilder(BUCKET_NAME, file.getOriginalFilename()).build(), file.getInputStream() );
可选优化
- 可以给GCS的文件设置ContentType,避免浏览器访问时直接下载而不是预览:
BlobInfo blobInfo = BlobInfo.newBuilder(BUCKET_NAME, file.getOriginalFilename()) .setContentType(file.getContentType()) .build();
- 文件名最好加上随机前缀/路径,避免重名文件覆盖。
内容的提问来源于stack exchange,提问作者OrganicWheel
相关产品推荐
相关产品推荐

