使用REST API上传Zip压缩包到Azure Blob Store时文件损坏问题求助
问题根本原因
你上传的Zip是二进制格式文件,现有代码的文件处理逻辑错误篡改了原始二进制内容,是文件损坏的核心原因:
readFileContent方法中,你将Zip的二进制字节做了多余的Base64编解码后,强制转换为String类型返回。二进制文件中存在大量不符合UTF-8/ASCII等字符编码规则的字节,转字符串过程中这些非法字节会被默认替换为统一的替换字符(对应你十六进制对比中看到的异常替换内容),最终写入Blob的就是篡改后的错误内容。- 文本文件因为所有字节都符合字符编码规则,转字符串过程不会出现内容替换,所以可以正常上传。
- 你尝试调整编码、更换HTTP库都无效,因为问题根源是二进制转字符串的错误处理逻辑,和编码、HTTP库无关。
解决方案
直接通过Unirest上传原始二进制内容,不要做任何转字符串的处理,Unirest原生支持传入File对象、byte数组作为请求体,会直接以二进制流传输,不会篡改内容。
修复后的代码
package blobQuickstart.blobAzureApp; import java.io.File; import org.junit.Test; import kong.unirest.HttpResponse; import kong.unirest.Unirest; public class StackOverflowExample { @Test public void uploadSmallZip() throws Exception { File testFile = new File("src/test/resources/zip/simple.zip"); String blobStore = "secretstore"; String contentType = "application/zip"; String url = "https://" + blobStore + ".blob.core.windows.net/naratest/" + testFile.getName() + "?sv=2020-02-10&ss=b&srt=o&sp=c&se=2021-09-07T20%3A10%3A50Z&st=2021-09-07T18%3A10%3A50Z&spr=https&sig=xvQTkCQcfMTwWSP5gXeTB5vHlCh2oZXvmvL3kaXRWQg%3D"; // 直接传入File对象作为body,Unirest会自动处理二进制流传输 HttpResponse<String> response = Unirest.put(url) .header("x-ms-blob-type", "BlockBlob") .header("Content-Type", contentType) .body(testFile) .asString(); if (!response.isSuccess()) { System.out.println(response.getBody()); throw new Exception("Failed to Upload File! Unexpected response code: " + response.getStatus()); } } }
验证说明
修复后上传完成后可以对比本地文件和Azure上下载文件的MD5值、文件大小,确认完全一致即可。
内容的提问来源于stack exchange,提问作者Alan Blyth
相关产品推荐
相关产品推荐

