java:文件下载
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
//文件下载
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取请求参数(文件名称)
String filename = request.getParameter("filename");
//2.使用字节输入流加载文件进内存
//2.1找到文件的服务器(真实)路径
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/img/" + filename);
//2.2用字节流关联
FileInputStream fis = new FileInputStream(realPath);
//3.设置response的响应头
//3.1设置响应头的类型
String mimeType = servletContext.getMimeType(filename);//获取文件的MIME类型
response.setHeader("content-type",mimeType);
//解决中文文件名问题
//1.获取user-agent请求头
String agent = request.getHeader("user-agent");
//2.使用工具类方法编译文件名
filename = DownLoadUtils.getFileName(agent, filename);
//3.2设置响应头打开方式
response.setHeader("content-disposition","attachment;filename="+filename);
//4.将输入流的的数据写出到输出流中
ServletOutputStream sos = response.getOutputStream();
//字节数组作为缓冲区
byte[] buff = new byte[1024*8];
//代表读到的个数
int len = 0;
while((len = fis.read(buff))!=-1){
sos.write(buff,0,len);
}
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
解决中文文件名的问题:
中文文件名显示不出来:
新建一个工具类:
import java.util.Base64;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class DownLoadUtils {
public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
//jdk8之后
Base64.Encoder base64Encoder = Base64.getEncoder();
filename = "=?utf-8?B?" + base64Encoder.encodeToString(filename.getBytes("utf-8")) + "?=";
//jdk8以及jdk8之前
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) +
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
}