zoukankan      html  css  js  c++  java
  • 来吧,教你JavaWeb中如何实现文件下载

    本文作者:乐字节-坑王老薛

    文件下载的方式

    • 超链接下载
    • 后台实现下载

    案例实操

    超链接下载

    当我们在 HTML 或 JSP 页面中使用标签时,原意是希望能够进行跳转,但当超链接遇到浏览器不识别的动态网页时则会自动下载。如果浏览器遇到能够直接显示的资源,浏览器就会默认显示出来,比如 txt,png,jpg 等。当然我们也可以通过 download 属性规定浏览器进行下载。但有些浏览器并不支持。

    默认下载

    <a href="upload/abc.zip">超链接下载</a>
    

    指定 download 属性下载

    <a href="upload/abc.txt" download="abcdef.txt">超链接下载</a>
    

    这里,download 也可以不写任何信息,会自动使用默认文件名。这样当用户打开浏览器点击链接的时候就会直接下载文件。

    后台实现下载

    Step1:需要通过 HttpServletResponse.setContentType 方法设置 Content-type 头字段的值,这样浏览器才能够使用某种方式或激活某个程序来处理相应 MIME 类型的数据,例 如 ”application/octet-stream” 或 ”application/x-msdownload” 等

    Step2:需要通过 HttpServletResponse.setHeader 方法设置 Content-Disposition 头的值为”attachment;filename=文件名”,filename提供了文件下载时的一个默认文件名

    Step3:读取下载文件,调用 HttpServletResponse.getOutputStream 方法返回的OutputStream对象来向客户端写入附件内容。

    public class DownLoadServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    		// 设置请求编码
    		request.setCharacterEncoding("UTF-8");
    		// 接受参数,得到需要被下载的文件的名称
    		String fileName = request.getParameter("fileName");
    		// 判断名字名是否为空
    		if(fileName == null || "".equals(fileName)){
    			// 提示
    			System.out.println("文件名不能为空");
    			return;
    		}
    		// 获取文件存放的真实路径
    		String path = request.getServletContext().getRealPath("/" + fileName);
    		// 通过文件路径和文件名得到file对象
    		File file = new File(path);
    		// 判断是否存在,并且是一个标准文件
    		if (file.exists() && file.isFile()){
    			// 设置相应类型 application/octet-stream
    			response.setContentType("application/x-msdownload");
    			// 设置头信息
    			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    			// 通过file对象得到输入流
    			FileInputStream in = new FileInputStream(file);
    			// 得到输出流
    			ServletOutputStream out = response.getOutputStream();
    			byte[] car = new byte[1024];
    			int len = 0;
    			while((len = in.read(car)) != -1){
    				out.write(car,0,len);
    			}
    			// 关闭流
    			in.close();
    			out.close();
    		} else {
    			System.out.println("文件路径不正确!");
    		}
    		
    	}
    
    }
    

    扩展~HTML表单编码

    HTML表单编码

    enctype 属性指定浏览器如何编码数据并将其呈现给服务器。

    此属性有三个允许值。

    • application/x-www-form-urlencoded
      默认编码。
      此编码无法用于将文件上传到服务器。
    • multipart/form-data
      此编码用于将文件上传到服务器。
    • text/plain
      此编码因浏览器而异。

    要理解不同编码的工作原理,我们创建了以下形式。

    <!DOCTYPE HTML>
    <html>
    <body>
      <form method="post" action="http://example.com/form">
        <input name="fave" /> 
        <input name="name" />
        <button>Submit Vote</button>
      </form>
    </body>
    </html>
    

    application/x-www-form-urlencoded

    如果使用application / x-www-form-urlencoded编码,每个数据项的名称和值都使用用于编码URL的相同方案进行编码。这是编码应用于示例形式的数据的方式:

    fave=Apples&name=FiratName+LastName
    

    特殊字符将替换为其HTML实体对应部分。数据项的名称和值由等号(=)分隔,数据/值元组由&符号(&)分隔。

    multipart/form-data

    multipart / form-data 编码往往仅用于上传文件。下面是示例表单中的数据如何编码:

    ------WebKitFormBoundary2desQWER543CDFGF
    
    Content-Disposition: form-data; name="fave" YourName
    ------WebKitFormBoundary2desQWER543CDFGF Content-Disposition: form-data; name="name" www.lezijie.cn
    ------WebKitFormBoundary2desQWER543CDFGF-- fave=Apple
    name=www.lezijie.cn
    

    multipart/plain

    主流浏览器以不同的方式对该编码进行编码。

    Google Chrome以与application / x-www-form-urlencoded方案相同的方式对数据进行编码,而Firefox对数据进行编码的方式如下:

    fave=xml
    name=www.lezijie.cn
    

    n

    主流浏览器以不同的方式对该编码进行编码。

    Google Chrome以与application / x-www-form-urlencoded方案相同的方式对数据进行编码,而Firefox对数据进行编码的方式如下:

    fave=xml
    name=www.lezijie.cn
    

    每个数据项都放在一行上,不会对特殊字符进行编码。

  • 相关阅读:
    poj 3616 Milking Time
    poj 3176 Cow Bowling
    poj 2229 Sumsets
    poj 2385 Apple Catching
    poj 3280 Cheapest Palindrome
    hdu 1530 Maximum Clique
    hdu 1102 Constructing Roads
    codeforces 592B The Monster and the Squirrel
    CDOJ 1221 Ancient Go
    hdu 1151 Air Raid(二分图最小路径覆盖)
  • 原文地址:https://www.cnblogs.com/lezijie/p/13543510.html
Copyright © 2011-2022 走看看