1、下载的servlet DownloadServlet.java
package cn.demo.download;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.demo.utils.DownUtils;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// 设置要下载的文件路径
String realPath = this.getServletContext().getRealPath("/WEB-INF/kk/郁金香.jpg");
File file = new File(realPath);
if (!file.exists()) {
throw new RuntimeException("文件已经被删除");
}
String filename = file.getName();
System.out.println("filename: " + filename);
// 处理下载文件名中文乱码问题
filename = DownUtils.getAttachmentFilement(filename, request.getHeader("user-agent"));
// 设置浏览器下载弹框
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
// 告知浏览器下载文件的mime类型
String mime = this.getServletContext().getMimeType(filename);
response.setContentType(mime);
// 以流的形式发送给浏览器
ServletOutputStream out = response.getOutputStream();
// 读取服务器文件
InputStream in = new FileInputStream(file);
int len = 0;
byte[] bytes = new byte[4 * 1024];// 每次读取4M
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);// 写入
}
// 关闭输入流
in.close();
}
}
2、DownUtils
public static String getAttachmentFilement(String filename, String header)
throws UnsupportedEncodingException {
if (header.contains("Firefox")) {// 火狐浏览器
filename = "=?utf-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?=";
} else {
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}