我创建了一个 Controller 来下载文件,它对于小文件工作正常,但对于较大的文件而不是下载,它只是在浏览器中打开文件(下载了 2kB 文件,但打开了 12kB 文件)。我知道从 Controller 下载文件有不同的选项,但我想知道我的代码中问题的根本原因是什么。
我的 Controller :
@GetMapping("/logs/getfile")
public void getFile(@RequestParam String logFile,HttpServletResponse response) {
try {
String directory = "C:\\Users\\user\\Documents\\";
InputStream is=new FileInputStream(new File(directory+logFile));
IOUtils.copy(is, response.getOutputStream());
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment; filename="+logFile);
response.flushBuffer();
}catch(IOException ex) {
ex.printStackTrace();
}
}
最佳答案
您使用的内容类型无效。要发送浏览器必须将其视为文件(二进制)的二进制数据,您必须使用 application/octet-stream
检查list of media-types有关 HTTP 协议(protocol)有效内容类型的完整列表
关于java - Controller 在浏览器中打开文件而不是下载它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59791349/