下载图片或者文件有那么几种方法,下面详细总结。
1,js方法
function downloadFile(url){
var elemIF = document.createElement("iframe");
elemIF.src = url;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
}
直接在js中调用这个方法就可以实现下载,下载文件显示在浏览器下面。
不过这种实现方法有一个问题,单纯的一个jsp页面或者html页面,直接使用这个方法是没有问题的,但是在程序开发的过程中往往就不那么单纯,大多是在弹出框中嵌套页面,如果下载方法在这个嵌套的页面中就可能会出现问题,可能会出现文件不下载,但是后台和浏览器中都没有报错,就是不下载。
出现这个原因就是下载页面嵌套过来后不是在iframe中。最简单的解决方法就是嵌套页面的时候用iframe,不过这种也不简单,如果用弹出框的形式的话,就麻烦至极了,不过还好,还有其他的方法实现下载。
2,js+后台
js:
//下载图片
function downloadFileT(path, fname){
$('#fileDownFrame').form('submit', {
url :'<%=request.getContextPath()%>/down/downLoadFile.action?filename='+encodeURI(encodeURI(fname))+'&filePath='+encodeURI(encodeURI(path)),
dataType : 'text/xml',
async:false,
success : function(data) {
。。。。。
}
});
}
html:
<form id="fileDownFrame" style="display:none; visibility:hidden;" method="post"></form>
action:
/**
* 下载附件
* @param request
* @param response
* @throws UnsupportedEncodingException
* @throws IOException
*/
@Action("downLoadFile")
public void downLoadFile() throws IOException {
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
//response.setContentType("text/Xml;charset=utf-8");
response.setContentType("application/octet-stream");
JSONObject json=new JSONObject();
try{
String path= URLDecoder.decode(request.getParameter("filePath"),"utf-8");//从页面获取要下载的文件的相对路径
String filename= URLDecoder.decode(request.getParameter("filename"),"utf-8");
if(!"".equals(path)){
path=path.replaceAll("\\\\", "/");
File file=new File(request.getSession()
.getServletContext().getRealPath("/")+path);//构造要下载的文件
if(file.exists()){
InputStream ins=new FileInputStream(file);//构造一个读取文件的IO流对象
BufferedInputStream bins=new BufferedInputStream(ins);//放到缓冲流里面
OutputStream outs=response.getOutputStream();//获取文件输出IO流
BufferedOutputStream bouts=new BufferedOutputStream(outs);
response.setContentType("application/x-msdownload");//设置response内容的类型
response.addHeader("Content-Length", "" + file.length());
response.setHeader("Content-disposition","attachment;filename="+ new String( filename.getBytes("gb2312"), "ISO8859-1" ));//设置头部信息
int bytesRead = 0;
int size=(int)file.length();
byte[] buffer = new byte[size];
//开始向网络传输文件流
while ((bytesRead = bins.read(buffer, 0, buffer.length)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();//这里一定要调用flush()方法
ins.close();
bins.close();
outs.close();
bouts.close();
// json.put("result", "success");
}else{
response.reset();
json.put("result", "none");
response.getWriter().print(json.toString());
System.out.println("下载的文件不存在");
}
}else{
json.put("result", "wrong");
response.getWriter().print(json.toString());
System.out.println("下载文件时参数错误");
}
}catch (Exception e) {
json.put("result", "error");
response.getWriter().print(json.toString());
e.printStackTrace();
}
}