java、javascript实现附件下载
在web开发中,经常需要开发“下载”这一模块,以下给出一个简单的例子。
在服务器端,使用java开发:
@RequestMapping(value = "download.html", method = RequestMethod.GET)
public void download(String resourceid, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("charset=UTF-8");
File file = new File(path);
response.setHeader("Content-Disposition", "attachment; filename=a");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
try {
fis = new FileInputStream(file.getAbsolutePath());
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
int bytesRead = 0;
byte[] buffer = new byte[5 * 1024];
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
}catch(E e){
}finally {
try {
bis.close();
bos.close();
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当我们在前端请求这个地址时,服务器先找出文件,设置响应头,然后通过流输出到浏览器端。
浏览器在头中发现该响应的主体是流文件,则自动会调用另存为的窗口,让用户保存下载。
这里有个关键就是Content-Disposition这个头属性,Content-Disposition是MIME协议的扩展,用于指示如何让客户端显示附件的文件。
它可以设置为两个值:
inline //在线打开
attachment //作为附件下载
这里我们设置的值为attachment,所以可以被识别为附件并下载。
上面讲了如何写服务器端,下面讲前端如何请求。
前端请求有三种方式:
1.Form
<form action='download.html' method='post'> <input type='submit'/> </form>
2.iframe
var iframe = "<iframe style='display:none' src='download.html'></iframe>" body.append(iframe);
当iframe被append到body中时,会自动请求下载链接。
3.open
window.open("download.html");
原文出处:http://blog.youkuaiyun.com/forevercjl/article/details/38557335