我试图让用户从服务器下载文件。我在控制器中使用 ServletOutputStream(这里是代码)
@RequestMapping(value = "/get-backup-file", method = RequestMethod.GET)
@ResponseBody
public void getBackupFile(
HttpServletRequest request,
HttpServletResponse response) throws MalformedURLException, IOException {
File backupFile = new File("PATH_TO_FILE");
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setContentLength((int)backupFile.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + "database backup" + "\"");
FileInputStream in = new FileInputStream(backupFile);
byte[] buffer = new byte[4096];
int length;
while( (length = in.read(buffer) ) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
我的客户端看起来像这样:
$.ajax({
url: 'URL_TOCONTROLLER_METHOD',
contentType: "application/octet-stream; charset=utf-8",
type: 'GET',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("error");
}
});
当我控制台记录数据时,它具有文件的内容,但我希望用户下载此文件,而不仅仅是打印。如何让用户将数据保存为文件?