使用RESTAPI上载到Azure Blob存储时,java Zip存档文件会损坏
我真的一直在用这一个碰壁我的头,上传文本文件是好的,但当我上传到我的blob商店压缩档案->;它已损坏,下载后无法打开。 将原始文件与通过Azure的文件进行十六进制比较(下图)表明发生了一些细微的替换,但我找不到更改/损坏的来源。 我曾尝试强制使用UTF-8/Ascii/UTF-16,但发现UTF-8可能是正确的,没有一个解决了这个问题。 我也尝试了不同的http库,但得到了相同的结果。 部署环境正在强制unirest,并且无法使用Microsoft API(该API似乎工作正常)
package blobQuickstart.blobAzureApp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Base64;
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";
UploadedFile testUploadedFile = new UploadedFile();
testUploadedFile.setName(testFile.getName());
testUploadedFile.setFile(testFile);
String contentType = "application/zip";
String body = readFileContent(testFile);
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";
HttpResponse<String> response = Unirest.put(url)
.header("x-ms-blob-type", "BlockBlob").header("Content-Type", contentType)
.body(body).asString();
if (!response.isSuccess()) {
System.out.println(response.getBody());
throw new Exception("Failed to Upload File! Unexpected response code: " + response.getStatus());
}
}
private static String readFileContent(File file) throws Exception {
InputStream is = new FileInputStream(file);
ByteArrayOutputStream answer = new ByteArrayOutputStream();
byte[] byteBuffer = new byte[8192];
int nbByteRead;
while ((nbByteRead = is.read(byteBuffer)) != -1)
{
answer.write(byteBuffer, 0, nbByteRead);
}
is.close();
byte[] fileContents = answer.toByteArray();
String s = Base64.getEncoder().encodeToString(fileContents);
byte[] resultBytes = Base64.getDecoder().decode(s);
String encodedContents = new String(resultBytes);
return encodedContents;
}
}
请帮忙
# 1 楼答案
默认情况下,Unirest文件处理程序将强制使用多部分正文-Azure不支持
字节数组可以按照以下方式直接提供:https://github.com/Kong/unirest-java/issues/248
# 2 楼答案
您正在从包含二进制数据的字节数组创建字符串。字符串仅适用于可打印字符。你只需要占用更多内存就可以进行多次无意义的编码/解码
如果内容是ZIP格式的,它是二进制的,只需返回字节数组即可。或者你可以对内容进行编码,但是你应该返回编码的内容。作为一个缺点,您在内存中完成这一切,限制了内容的潜在大小