我需要从输出路径下载excel文件,但我无法这样做。如何使用Jquery和Spring Controller从服务器下载文件?
这里是我的jQuery代码
$("#download").click(function(){
if($(this).data('clicked', true)){
$.ajax({
type:'POST',
url :"downloadFile",
contentType : "application/json; charset=utf-8",
success: function(result) {
alert('File Download');
},
error:function(exception){
alert('Error Occured during file Download');
console.log('exception',exception);
}
});
}
});
这是我的控制器代码:
@PostMapping("downloadFile")
@ResponseBody
public void downloadResult(HttpServletRequest request, HttpServletResponse response)throws Exception{
try {
File file = new File(outputPath + fileName);
if (file.exists()) {
String mimeType = context.getMimeType(file.getPath());
System.out.println();
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentLength((int) file.length());
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
int b = -1;
while ((b = fis.read(buffer)) != -1) {
os.write(buffer, 0, b);
}
fis.close();
os.close();
} else {
System.out.println("Requested " + fileName + " file not found!!");
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
我需要它出现在浏览器中下载或保存选项的弹出。
帮助表示赞赏,感谢
UPDATE:
我无法打开该文件,请查看下面的图像。
所做的更改按照#StanislavL答案
控制器:
@GetMapping("/downloadFile")
public void downloadResult(HttpServletRequest request, HttpServletResponse response)throws Exception{
//CODE
}
JSP页面(JavaScript)的
$("#download").click(function(){
if($(this).data('clicked', true)){
window.location="http://localhost:8080/IRI-AXCO/downloadFile";
}
});
你会得到什么错误?请通过网址为“/ downloadFile” –
其实这就是我需要下载的Excel文件,所有的Excel数据都在浏览器控制台 –