本文做者:乐字节-坑王老薛html
当咱们在 HTML 或 JSP 页面中使用标签时,原意是但愿可以进行跳转,但当超连接遇到浏览器不识别的动态网页时则会自动下载。若是浏览器遇到可以直接显示的资源,浏览器就会默认显示出来,好比 txt,png,jpg 等。固然咱们也能够经过 download 属性规定浏览器进行下载。但有些浏览器并不支持。java
默认下载浏览器
<a href="upload/abc.zip">超连接下载</a>
指定 download 属性下载服务器
<a href="upload/abc.txt" download="abcdef.txt">超连接下载</a>
这里,download 也能够不写任何信息,会自动使用默认文件名。这样当用户打开浏览器点击连接的时候就会直接下载文件。app
Step1:须要经过 HttpServletResponse.setContentType
方法设置 Content-type 头字段的值,这样浏览器才可以使用某种方式或激活某个程序来处理相应 MIME 类型的数据,例 如 ”application/octet-stream” 或 ”application/x-msdownload” 等 ide
Step2:须要经过 HttpServletResponse.setHeader
方法设置 Content-Disposition 头的值为”attachment;filename=文件名”,filename提供了文件下载时的一个默认文件名post
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("文件路径不正确!"); } } }
enctype
属性指定浏览器如何编码数据并将其呈现给服务器。url
此属性有三个容许值。code
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
编码,每一个数据项的名称和值都使用用于编码URL的相同方案进行编码。这是编码应用于示例形式的数据的方式:
fave=Apples&name=FiratName+LastName
特殊字符将替换为其HTML实体对应部分。数据项的名称和值由等号(=)分隔,数据/值元组由&符号(&)分隔。
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
主流浏览器以不一样的方式对该编码进行编码。
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
每一个数据项都放在一行上,不会对特殊字符进行编码。