前台:
$.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();