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提交方式,前台是不会弹出框的
后台传来的 url是什么格式的 或者说路径是哪里的