文件下载的两种方式:
* 第一种:超链接下载,直接将文件的路径写到超链接的href中。前提是:文件类型不支持。如果支持浏览器会直接打开文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>下载页面</h1>
<a href="/day/download/傻子.jpg">傻子.jpg</a><br />
<a href="/day/download/bbb.txt">bbb.txt</a><br />
<a href="/day/download/bbb.zip">bbb.zip</a><br />
</body>
</html>
浏览器支持的jpg、txt等格式文件点击下载会直接在浏览器打开,并不会弹出下载界面。
当点击下载浏览器不支持的zip格式文件时,会弹出下载界面。
* 第二种:手动编写Servlet代码设值属性值,完成文件的下载
* 设值两个头和一个流
* Content-Type :文件的MIME的类型.
* Content-Disposition :以下载的形式打开文件.
* InputStream :文件的输入流.
Download.html(文件下载页面)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<h2>
<h3>下载列表</h3>
<a href="/day/downloadServlet?filename=傻子.jpg">傻子.jpg</a><br>
<a href="/day/downloadServlet?filename=bbb.txt">bbb.txt</a><br>
<a href="/day/downloadServlet?filename=bbb.zip">bbb.zip</a><br>
</h2>
</body>
</html>
downloadServlet.java(文件下载Servlet)
package com.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Encoder;
/**
* @author 侯青华
* @version 创建时间:2018年3月9日 下午2:09:02
*/
public class downloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.接收参数
String filename = new String(request.getParameter("filename").getBytes("ISO-8859-1"), "UTF-8");
// 2.完成文件下载:
// 2.1设置Content-Type头
String type = this.getServletContext().getMimeType(filename);
response.setHeader("Content-Type", type);
// 2.3设置文件的InputStream.
String realPath = this.getServletContext().getRealPath("/download/" + filename);
// 根据浏览器的类型处理中文文件的乱码问题:
String agent = request.getHeader("User-Agent");
if (agent.contains("Firefox")) {
filename = base64EncodeFileName(filename);
} else {
filename = URLEncoder.encode(filename, "UTF-8");
}
// 2.2设置Content-Disposition头
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
InputStream is = new FileInputStream(realPath);
// 获得response的输出流:
OutputStream os = response.getOutputStream();
int len = 0;
byte[] chs = new byte[1024];
while ((len = is.read(chs)) != -1) {
os.write(chs, 0, len);
}
is.close();
}
public static String base64EncodeFileName(String fileName) {
BASE64Encoder base64Encoder = new BASE64Encoder();
try {
return "=?UTF-8?B?" + new String(base64Encoder.encode(fileName.getBytes("UTF-8"))) + "?=";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
总结:下载文件时使用第二种方案,注意处理中文文件乱码问题。