标题 | java、javascript实现附件下载示例 |
范文 | 在web开发中,经常需要开发“下载”这一模块,以下给出一个简单的例子。 在服务器端,使用java开发: view sourceprint? 01 @RequestMapping(value = "download.html", method = RequestMethod.GET) 02 public void download(String resourceid, HttpServletRequest request, HttpServletResponse response) { 03 response.setContentType("charset=UTF-8"); 04 File file = new File(path); 05 response.setHeader("Content-Disposition", "attachment; filename=a"); 06 BufferedInputStream bis = null; 07 BufferedOutputStream bos = null; 08 OutputStream fos = null; 09 InputStream fis = null; 10 try { 11 fis = new FileInputStream(file.getAbsolutePath()); 12 bis = new BufferedInputStream(fis); 13 fos = response.getOutputStream(); 14 bos = new BufferedOutputStream(fos); 15 int bytesRead = 0; 16 byte[] buffer = new byte[5 * 1024]; 17 while ((bytesRead = bis.read(buffer)) != -1) { 18 bos.write(buffer, 0, bytesRead); 19 } 20 bos.flush(); 21 }catch(E e){ 22 }finally { 23 try { 24 bis.close(); 25 bos.close(); 26 fos.close(); 27 fis.close(); 28 } catch (IOException e) { 29 e.printStackTrace(); 30 } 31 } 32 } 当我们在前端请求这个地址时,服务器先找出文件,设置响应头,然后通过流输出到浏览器端。 浏览器在头中发现该响应的主体是流文件,则自动会调用另存为的窗口,让用户保存下载。 这里有个关键就是Content-Disposition这个头属性,Content-Disposition是MIME协议的扩展,用于指示如何让客户端显示附件的文件。 它可以设置为两个值: inline //在线打开 attachment //作为附件下载 这里我们设置的值为attachment,所以可以被识别为附件并下载。 上面讲了如何写服务器端,下面讲前端如何请求。 前端请求有三种方式: 1.Form view sourceprint?1 <form action='download.html' method='post'> 2 <input type='submit'/> 3 </form> 2.iframe view sourceprint?1 var iframe = "<iframe style='display:none' src='download.html'></iframe>" 2 body.append(iframe); 当iframe被append到body中时,会自动请求下载链接。 3.open view sourceprint?1 window.open("download.html"); |
随便看 |
|
在线学习网范文大全提供好词好句、学习总结、工作总结、演讲稿等写作素材及范文模板,是学习及工作的有利工具。