以下是用于下载文件的控制器。这些文件可以是多种类型,例如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();
}
}
答案 0 :(得分:1)
这是因为您已将mime类型设置为octet-stream
使用Files.probeContentType(path)获取文件对象的正确mime类型并将其替换为octet-stream
或者使用您自己的逻辑从this list
指定mime类型