您好,欢迎访问一九零五行业门户网

java、javascript实现附件下载示例_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

2.iframe
var iframe = body.append(iframe);
​当iframe被append到body中时,会自动请求下载链接。
3.open
window.open(download.html);
其它类似信息

推荐信息