带中文名称的文件下载

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>下载页面</title>
</head>
<body>
<a href="/day15/img/九尾.jpg">图片1</a>
<a href="/day15/img/1.avi">视屏</a>
<hr/>
<a href="/day15/downloadServlet?filename=九尾.jpg">图片1</a>
<a href="/day15/downloadServlet?filename=1.avi">视屏</a>

</body>
</html>

package com.hopetesting.web.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;
}
}



package com.hopetesting.web.download;

import com.hopetesting.web.utils.DownLoadUtils;
import sun.management.Agent;

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;

/**
* @author newcityman
* @date 2019/9/2 - 0:05
*/
@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 context = request.getServletContext();
String realPath = context.getRealPath("/img/" + filename);
// 2.2、用字节流关联
FileInputStream fis = new FileInputStream(realPath);
// 3、设置response的响应头
// 3.1信息content-type
String mimeType = context.getMimeType(filename);
response.setHeader("content-type",mimeType);
// 3.2设置响应头信息content-disposition
//处理中文文件名乱码问题
// 获取user-agent请求头
String agent = request.getHeader("user-agent");
// 使用工具类方法编码文件名即可
filename= DownLoadUtils.getFileName(agent, filename);
response.setHeader("content-disposition","attachment;filename="+filename);
// 4、将输入流的数据写出到输出流中
ServletOutputStream sos = response.getOutputStream();
int len=0;
byte[] buff = new byte[1024*8];
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);
}
}
 

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/11444417.html