ajax请求后台下载zip压缩文件问题,后台返回的是流前台不提示下载。附上ajax请求代码合后台代码
前台:$.ajax({type:"POST",url:"app/downloadProduct",data:{nid:nid,name:name},dataType:"t...
前台:
$.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();
界面使用href=“”的方式能下载,现在不用这种方式,前台发ajax请求后台返回流怎么处理?或者前台发ajax请求后台返回下载url也不显示下载条。 展开
$.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();
界面使用href=“”的方式能下载,现在不用这种方式,前台发ajax请求后台返回流怎么处理?或者前台发ajax请求后台返回下载url也不显示下载条。 展开
- 你的回答被采纳后将获得:
- 系统奖励15(财富值+成长值)+难题奖励30(财富值+成长值)
1个回答
展开全部
不好意思,ajax不支持下载功能
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |