我想讓用戶從服務器上下載文件。 我使用ServletOutputStream的在我的控制器(這裏是代碼)如何讓用戶使用ajax成功方法下載文件?
@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");
}
});
當我CONSOLE.LOG它具有文件的內容的數據,但我希望這個文件被下載到用戶,而不僅僅是打印。如何讓用戶將數據保存爲文件?
http://stackoverflow.com/questions/6722716/how-to-download-file-from-server-using-jquery-ajax-and-spring-mvc-3 – hgoebl