jpw_980319116
jpw_980319116
2015-05-25 01:13

ajax请求后台下载zip压缩文件问题,后台返回的是流前台不提示下载。附上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();
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答