1.目的
下载远程文件
效果如图
IE下
chrome下
2.流程
1.提交下载请求(有坑,不能用ajax,或ajaxsubmit直接提交)
2.读取文件
3.response回显
3.代码
1.前台jsp/html
这个form是用来提交下载请求的, 其中的input可以传递一些参数, action就是后台的request请求地址
<%-- 用于下载提交请求--%>
<form id="downloadForm" action="${BASEPATH}annexManage/download" method="post" type="hidden">
<input id="filePath" name="filePath" value="" type="hidden"/>
<input id="fileName" name="fileName" value="" type="hidden"/>
<input id="extName" name="extName" value="" type="hidden"/>
</form>
</div>
2.js代码
给input的属性赋值
使用submit提交请求
一定要这样提交,不能用$.ajax或者 ajaxsubmit。 不然不会下载
$("#filePath").val(filePath);
$("#fileName").val(rowData.aFilename);
$("#extName").val(rowData.aFiletype);
$("#downloadForm").submit();
3.java后台代码
@RequestMapping(value = "/getFileStream/", method = RequestMethod.GET)
public void pdfStreamHandler(HttpServletRequest request, HttpServletResponse response) {
String fileSrc=(String) request.getSession().getAttribute("fileSrc");
logger.debug("获取的预览文件路径是 "+ fileSrc);
File file = new File(fileSrc);
try {
byte[] data = null;
try {
String strUrl = fileSrc.trim();
URL url=new URL(strUrl);
//打开请求连接
URLConnection connection = url.openConnection();
HttpURLConnection httpURLConnection=(HttpURLConnection) connection;
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 取得输入流,并使用Reader读取
int responseCode=((HttpURLConnection) connection).getResponseCode();
BufferedInputStream bis=null;
bis = new BufferedInputStream(httpURLConnection.getInputStream());
ServletOutputStream sos = response.getOutputStream();
//BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
int b;
while((b = bis.read())!=-1) {
sos.write(b);
}
sos.close();
bis.close();
} catch (Exception e) {
System.out.println("pdf文件处理异常:" + e);
}
}
catch (Exception e) {
return;
}
}