问题描述
- ajax请求后台下载zip压缩文件问题,后台返回的是流前台不提示下载。附上ajax请求代码合后台代码
-
前台:
$.ajax({
type:"POST",
url:"app/downloadProduct",
data:{nid:nid,name:name},
dataType:"text",
success:function(data){
console.log(data);
if(data!=null){
alert("url="+data);
window.location.href = data;
}else{
alert("资源获取失败!");
}
}
});
后台:
public static void downloadExportFileByResponse(String downloadFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("--------downloadFile---------"+downloadFile);
if(downloadFile==null||"".equals(downloadFile))
{
throw new Exception("文件名为空,下载文件失败!");
}
try {
byte[] buffer = new byte[256];
InputStream is = new FileInputStream(downloadFile);try { downloadFile = downloadFile.substring(downloadFile.lastIndexOf(File.separator) + 1); downloadFile = URLEncoder.encode(downloadFile, "UTF-8"); } catch(Exception e) { e.printStackTrace(); } File filename = new File(downloadFile); //response.setContentType("text/plain"); response.addHeader("content-type","application/x-msdownload");//浏览器自己辨别文件类型 response.addHeader("Content-Disposition", "attachment; filename=" + filename.getName()); response.addHeader("Content-Length", String.valueOf(is.available())); int nRead = 0; while((nRead = is.read(buffer)) > 0) response.getOutputStream().write(buffer, 0, nRead); is.close();
解决方案
$.ajax({
type:"POST",
url:"app/downloadProduct",
data:{nid:nid,name:name},
dataType:"text",
success:function(data){
console.log(data);
if(data!=null){
alert("url="+data);
window.location.href = data;
}else{
alert("资源获取失败!");
}
}
});
为什么不直接改成:
window.open("app/downloadProduct","_blank");
解决方案二:
没人回答?补充问题:前台界面用href=“”的方式是能下载的,现在不想用href的方法,只用ajax请求后台action处理。求指教。。
解决方案三:
如果是ajax提交方式,前台是不会弹出框的
时间: 2024-11-01 23:16:13