案例需求分析与步骤
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c3fa9b93004f6bb18171e60b8031c72e.png)
下载页面的代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/08_response/downloadServlet?filename=素描1.jpg">素描风景</a>
<a href="/08_response/downloadServlet?filename=夏天的风.mp3">夏天的风</a>
</body>
</html>
文件下载的Servlet代码部分
package pers.cb.web.download;
import pers.cb.web.utils.DownLoadUtils;
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 {
String filename = request.getParameter("filename");
ServletContext servletContext = this.getServletContext();
String realPath = null;
if (filename.endsWith(".jpg"))
{
realPath = servletContext.getRealPath("/img/" + filename);
}
if (filename.endsWith(".mp3"))
{
realPath = servletContext.getRealPath("/music/" + filename);
}
System.out.println(realPath);
FileInputStream fis = new FileInputStream(realPath);
String mimeType = servletContext.getMimeType(filename);
response.setHeader("content-type",mimeType);
String agent = request.getHeader("user-agent");
filename = DownLoadUtils.getFileName(agent, filename);
response.setHeader("content-disposition","attachment;filename=" + filename);
ServletOutputStream sos = response.getOutputStream();
byte[] bytes = new byte[1024 * 8];
int len = 0;
while((len = fis.read(bytes)) != -1)
{
sos.write(bytes,0,len);
}
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
中文文件名的工具类
package pers.cb.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"))
{
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;
}
}