简体   繁体   中英

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. The issue is that the file type downloaded is always "File" instead of pdf, excel or 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

Either use Files.probeContentType(path) to get the correct mime type of the file object and replace it in place of octet-stream

Or use your own logic to specify a mime type there from this list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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