簡體   English   中英

服務器上的Java下載文件無法識別文件類型

[英]Java download file from server cannot identify file type

以下是用於下載文件的控制器。 文件可以是多種類型,例如pdf,excel和doc。 問題是下載的文件類型始終是“文件”,而不是pdf,excel或doc。 我必須手動選擇一個應用程序才能打開文件。 有人知道哪里出問題了嗎? 謝謝!

@RequestMapping(value="/download/system-of-record", method = RequestMethod.GET)
public void systemOfRecordDownload(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
    int formId = Integer.parseInt(request.getParameter("id"));
    Form form = formService.findFormByPrimaryKey(formId);
    String formName = form.getName();
    String formPath = form.getInternalLink();
    response.reset();
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + formName + "\"");

    try {
        File f = new File(formPath);
        OutputStream os = response.getOutputStream();
        byte[] buf = new byte[8192];

        FileInputStream is = new FileInputStream(f);

        int readByte = 0;

        while ((readByte = is.read(buf, 0, buf.length)) > 0) {
            os.write(buf, 0, readByte);
            os.flush();
        }
        os.close();
        is.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

那是因為您已將mime類型設置為八位字節流

使用Files.probeContentType(path)來獲取文件對象的正確mime類型並將其替換為八位字節流

或使用您自己的邏輯來從那里指定一個MIME類型列表

暫無
暫無

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

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