簡體   English   中英

文件開頭的附加“ 2000”字符串([32 30 30 30]字節)

[英]Additional “2000” String ([32 30 30 30] bytes) at the beginning of a file

我有一個非常奇怪的問題,我找不到解決方案。

我有一個簡單的測試servlet,它在響應中流式傳輸一個小的pdf文件:

public class TestPdf extends HttpServlet implements Servlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        File file = new File(getServletContext().getRealPath("/lorem.pdf"));

        response.setContentType("application/pdf");

        ServletOutputStream out = response.getOutputStream();

        InputStream in = new FileInputStream(file);

        byte[] bytes = new byte[10000];

        int count = -1;

        while ((count = in.read(bytes)) != -1) {
            out.write(bytes, 0, count);
        }

        in.close();

        out.flush();
        out.close();

    }

}

如果我使用瀏覽器調用servlet url,curl,wget,一切都很好,但是當我使用簡單的TCL腳本調用它時,如下所示:

#!/usr/bin/tclsh8.5

package require http;

set testUrl "http://localhost:8080/test/pdf"
set httpResponse [http::geturl "$testUrl" -channel stdout]

該文件的開頭有一個“ 2000”字符串,損壞了pdf。

這個問題似乎與Tomcat或JDK版本無關,因為我可以在JDK 1.5.0_22 Tomcat 5.5.36和JDK 1.8.0_74和Tomcat 8.5.15的開發環境(Ubuntu 16.04)上重現該問題。

正如其他人所指出的,您看到的是一個塊的開始,即該塊包含的八位字節數。 要從Tcl客戶端處理此問題(而不是通過從Tomcat POV關閉分塊的傳輸編碼),您需要在http::geturl省略-channel選項:

package require http;

set testUrl "http://localhost:8080/test/pdf"
set httpResponse [http::geturl "$testUrl"]
fconfigure stdout -translation binary; # turn off auto-encoding on the way out
puts -nonewline stdout [http::data $httpResponse]

這應該正確地將分塊的內容遷移為一件。 背景是我上次檢查時,使用-channel選項無法處理分塊內容。

我從未使用過TCL,但是這是您如何編寫通用文件下載servlet的方法:

public class DownloadServlet extends HttpServlet {
    private final int BUFFER_SIZE = 10000;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {

        String filename = "test.pdf";
        String pathToFile = "..../" + filename;

        resp.setContentType("application/pdf");
        resp.setHeader("Content-disposition", "attachment; filename=" + filename);

        try(InputStream in = req.getServletContext().getResourceAsStream(pathToFile);
          OutputStream out = resp.getOutputStream()) {

            byte[] buffer = new byte[BUFFER_SIZE];
            int numBytesRead;

            while ((numBytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, numBytesRead);
            }
        }
    }
}

希望這段代碼對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM