标签:url nload att 乱码问题 https stat class his The
实现文件下载有个中文乱码问题,所以先来个工具类
package cn.itcast.utils;
import sun.misc.BASE64Encoder;
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")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
}
接下来就是servlet类的实现:
@WebServlet(name = "DownloadServlet",urlPatterns = "/download3")
public class DownloadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.获取文件名
String filename = request.getParameter("filename");
// 2.获取真实路径
// 2.1 获取ServletContext
ServletContext servletContext = this.getServletContext();
// 2.2 根据文件存储的位置,选择路径,本人的路径是web下的upload下的文件
String realPath = servletContext.getRealPath("/upload/" + filename);
// 3.设置响应头
// 3.1 设置content-type
response.setHeader("content-type",servletContext.getMimeType(filename));
// 3.2 解决中文乱码
String agent = request.getHeader("user-agent");
filename = DownLoadUtils.getFileName(agent,filename);
// 3.3 设置content-disposition
response.setHeader("content-disposition","attachment;filename=" + filename);
// 4.标准的IO流
FileInputStream fis = new FileInputStream(realPath);
ServletOutputStream sos = response.getOutputStream();
byte[] b = new byte[1024 * 8];
int len = 0;
while((len = fis.read(b)) != -1){
sos.write(b,0,len);
}
fis.close();
sos.close();
}
}
标签:url nload att 乱码问题 https stat class his The
原文地址:https://www.cnblogs.com/wadmwz/p/9528762.html