java、javascript实现附件下载示例
在web开发中,经常需要开发“下载”这一模块,以下给出一个简单的例子。
在服务器端,使用java开发:
@RequestMapping(value="download.html",method=RequestMethod.GET)
publicvoiddownload(Stringresourceid,HttpServletRequestrequest,HttpServletResponseresponse){
response.setContentType("charset=UTF-8");
Filefile=newFile(path);
response.setHeader("Content-Disposition","attachment;filename=a");
BufferedInputStreambis=null;
BufferedOutputStreambos=null;
OutputStreamfos=null;
InputStreamfis=null;
try{
fis=newFileInputStream(file.getAbsolutePath());
bis=newBufferedInputStream(fis);
fos=response.getOutputStream();
bos=newBufferedOutputStream(fos);
intbytesRead=0;
byte[]buffer=newbyte[5*1024];
while((bytesRead=bis.read(buffer))!=-1){
bos.write(buffer,0,bytesRead);
}
bos.flush();
}catch(Ee){
}finally{
try{
bis.close();
bos.close();
fos.close();
fis.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
当我们在前端请求这个地址时,服务器先找出文件,设置响应头,然后通过流输出到浏览器端。
浏览器在头中发现该响应的主体是流文件,则自动会调用另存为的窗口,让用户保存下载。
这里有个关键就是Content-Disposition这个头属性,Content-Disposition是MIME协议的扩展,用于指示如何让客户端显示附件的文件。
它可以设置为两个值:
inline//在线打开
attachment//作为附件下载
这里我们设置的值为attachment,所以可以被识别为附件并下载。
上面讲了如何写服务器端,下面讲前端如何请求。
前端请求有三种方式:
1.Form
<formaction='download.html'method='post'> <inputtype='submit'/> </form>
2.iframe
variframe="<iframestyle='display:none'src='download.html'></iframe>" body.append(iframe);
当iframe被append到body中时,会自动请求下载链接。
3.open
window.open("download.html");热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下