繁体   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