简体   繁体   English

服务器上的Java下载文件无法识别文件类型

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

Below is the controller for downloading files. 以下是用于下载文件的控制器。 The files can be multiple types, such as pdf, excel and doc. 文件可以是多种类型,例如pdf,excel和doc。 The issue is that the file type downloaded is always "File" instead of pdf, excel or doc. 问题是下载的文件类型始终是“文件”,而不是pdf,excel或doc。 I have to manually choose a application to open the file. 我必须手动选择一个应用程序才能打开文件。 Does anyone know what is wrong? 有人知道哪里出问题了吗? Thanks! 谢谢!

@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();
    }
}

Thats because you have set the mime type to octet-stream 那是因为您已将mime类型设置为八位字节流

Either use Files.probeContentType(path) to get the correct mime type of the file object and replace it in place of octet-stream 使用Files.probeContentType(path)来获取文件对象的正确mime类型并将其替换为八位字节流

Or use your own logic to specify a mime type there from this list 或使用您自己的逻辑来从那里指定一个MIME类型列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM