首页 > 解决方案 > 使用 REST API 上传到 Azure Blob Store 时,Zip 档案损坏

问题描述

我一直在用这个把头撞到墙上,上传文本文件很好,但是当我将一个 zip 存档上传到我的 blob 商店时 - >它被损坏了,一旦下载就无法打开。对通过 Azure 的原始文件与文件进行十六进制比较(下图)显示发生了一些微妙的替换,但我找不到更改/损坏的来源。我曾尝试强制使用 UTF-8/Ascii/UTF-16,但发现 UTF-8 可能是正确的,没有解决问题。我也尝试了不同的 http 库,但得到了相同的结果。部署环境迫使 unirest,并且不能使用 Microsoft 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;
    }
}

十六进制比较

请帮忙!

标签: javaazureresthttpazure-blob-storage

解决方案


    byte[] resultBytes = Base64.getDecoder().decode(s);
    String encodedContents = new String(resultBytes);

您正在从包含二进制数据的字节数组创建一个字符串。字符串仅用于可打印字符。您进行多次毫无意义的编码/解码只是占用更多内存。

如果内容是 ZIP 格式,它是二进制的,只需返回字节数组。或者您可以对内容进行编码,但您应该返回已编码的内容。作为一个弱点,你在内存中做这一切,限制了内容的潜在大小。


推荐阅读