升级Google Cloud Storage依赖版本后Java文件上传功能失败
解决Google Cloud Storage客户端26.20.0+版本上传空文件时的Content-Range解析错误
问题背景
将Google Cloud Libraries BOM从26.19.0升级至26.20.0及以上版本后,使用storage.createFrom()批量上传目录文件时触发StorageException,错误核心为GCS服务器返回解析Content-Range标头失败,请求头中出现无效格式的content-range: bytes 0--1/0,此问题由客户端处理空文件的可恢复上传逻辑缺陷导致。
核心解决方案
针对空文件单独处理,禁用可恢复上传特性——空文件无需可恢复上传,且新版本客户端在此场景下的请求头构造存在格式错误。修改后的核心代码如下:
public void uploadFiles(String projectId, String bucketName, Path sourceDirectory){ var storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService(); try(var files = java.nio.file.Files.walk(sourceDirectory)){ files.forEach(file -> { // 跳过目录节点 if (java.nio.file.Files.isDirectory(file)) { return; } var blobId = BlobId.of(bucketName, getBlobPath(file)); var blobInfo = BlobInfo.newBuilder(blobId).build(); try { // 判断是否为空文件 if (java.nio.file.Files.size(file) == 0) { // 空文件禁用可恢复上传,使用简单上传模式 storage.createFrom(blobInfo, file, BlobWriteOption.detectContentType(), BlobWriteOption.disableResumableUpload()); } else { // 非空文件保留原有可恢复上传逻辑 storage.createFrom(blobInfo, file, BlobWriteOption.detectContentType()); } } catch (IOException e) { throw new RuntimeException("Failed to process file: " + file.getFileName(), e); } } ); } }
问题原因说明
在26.20.0+版本的google-cloud-storage客户端中,处理空文件的可恢复上传请求时,错误生成了不符合HTTP标准的Content-Range头(bytes 0--1/0),GCS服务器无法解析该格式,直接返回400 Bad Request错误。通过对空文件禁用可恢复上传,客户端会切换至简单上传模式,避免构造错误的请求头,从而修复该问题。
若业务无需保留空文件,也可直接在遍历逻辑中跳过空文件节点,根据实际需求调整即可。
内容的提问来源于stack exchange,提问作者Tahjid Ashfaque
相关产品推荐
相关产品推荐

