我的 base64 编码 byte[] 流在通过 http 响应发送后有额外的字符

My base64 encoded byte[] stream has extra characters after sent through a http response

我将 pdf 编码为 base64 字节 [] 流,我想将其作为 http 响应发送到浏览器。问题是浏览器加载pdf失败

我比较了打印到 IDE 控制台和浏览器控制台的 base 64 字符串。 IDE控制台的是正确的,浏览器的有多余的字符。

那么,我的 base64 byte[] 流在作为 http 响应发送时不知何故被破坏了?我该如何解决?

L.e。 : 代码

    FileInputStream inputFileInputStream = null;
    ServletOutputStream outputFileOutputStream = null;

    File exportFile = new File(exportedReport);
    int fileSize = (int) exportFile.length();
    String fullPathToExport = exportFile.getAbsolutePath();
    File fullPathFile = new File(fullPathToExport);

    try {
        // test to see if the path of the file is correct
        System.out.println("The file is located at: "
                + exportFile.getAbsolutePath());

        response.reset();
        response.setContentType("application/pdf");
        response.setContentLength(fileSize);
        response.addHeader("Content-Transfer-Encoding", "base64");
        response.setHeader( "Content-Disposition", "inline; filename=\"" + exportedReport +"\"");


        inputFileInputStream = new FileInputStream(fullPathFile);
        outputFileOutputStream = response.getOutputStream();

        if (bytesToRead == -1) {
            bytesToRead = (int)fullPathFile.length();
        }
        byte[] buffer = new byte[bytesToRead];
        int bytesRead = -1;

        while((inputFileInputStream != null) && ((bytesRead = inputFileInputStream.read(buffer)) != -1)){ 

            if (codec.equals("base64")) {
                //outputFileOutputStream.write(Base64.encodeBytes(buffer).getBytes("UTF-8"), 0, bytesToRead);

                outputFileOutputStream.write(org.apache.commons.codec.binary.Base64.encodeBase64(buffer));

            } else {
                outputFileOutputStream.write(buffer, 0, bytesToRead);
            }
        }
        inputFileInputStream.close();
        outputFileOutputStream.flush();
        outputFileOutputStream.close();

您的代码存在一个主要问题:

您发送的不是一个 base64 编码数据部分,而是多个 base64 编码数据部分(串联)。但是两个或多个base64编码的数据部分不等于一个base64编码的数据部分。

示例:

base64("This is a test") -> "VGhpcyBpcyBhIHRlc3Q="
base64("This ")+base64("is a ")+base64("test") -> "VGhpcyA=aXMgYSA=dGVzdA=="

您应该使用 org.apache.commons.codec.binary.Base64InputStream 而不是 Base64.encodeBase64() 实用方法。通过它读取整个FileInputStream,你将得到一个有效的base64编码数据流。

反正你做的事情是没有必要的。您可以通过 HTTP 传输任何 8 位数据而无需进一步编码。