我需要从输出路径下载excel文件,但我无法这样做。
这是我的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;
}
我需要一个弹出窗口,用于在浏览器中下载或保存选项。
感谢帮助, 感谢
更新
我无法打开文件,请查看下面的图片。
根据#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";
}
});
答案 0 :(得分:0)
映射应从/
将映射更改为@PostMapping("/downloadFile")
也不需要AJAX调用。您可以使用普通的GET映射,只需设置window.location = TheURL