我正在尝试实施一项服务,该服务会自动使用请求的文件开始下载。
这是我的AJAX呼叫:
function downloadFile(fileName) {
$.ajax({
url : SERVICE_URI + "files/" + fileName,
contentType : 'application/json',
type : 'GET',
success : function (data)
{
alert("done!");
},
error: function (error) {
console.log(error);
}
});
}
这是我的Spring Service方法GET:
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void getFile(@PathVariable("file_name") String fileName,
HttpServletResponse response) {
try {
// get your file as InputStream
FileInputStream fis = new FileInputStream( fileName + ".csv" );
InputStream is = fis;
// copy it to response's OutputStream
ByteStreams.copy(is, response.getOutputStream());
response.setContentType("text/csv");
response.flushBuffer();
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}
}
当我的客户端从服务器请求现有文件时,将执行AJAX
success()
方法,但该文件甚至没有下载。我做错什么了吗? 最佳答案
不要使用ajax,只需将window.location.href设置为文件的URL,然后在服务器脚本中设置http内容处理标头即可强制浏览器保存文件。
function downloadFile(fileName) {
window.location.href = SERVICE_URI + "files/" + fileName;
}