在上一篇中,下载的文件的名称都是英文的,若换成中文的,客户端在下载时会出现中文乱码问题。
在服务器端加入一个新的文件(美女.jpg)
将download.html页面进行修改(添加了一个美女.jpg的下载链接):
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 </head> 7 <body> 8 <h1>文件下载</h1> 9 <a href="/Zhan_Web_Servlet/filedownload?filename=a.flv">a.flv</a><br> 10 <a href="/Zhan_Web_Servlet/filedownload?filename=a.jpg">a.jpg</a><br> 11 <a href="/Zhan_Web_Servlet/filedownload?filename=a.mp3">a.mp3</a><br> 12 <a href="/Zhan_Web_Servlet/filedownload?filename=a.mp4">a.mp4</a><br> 13 <a href="/Zhan_Web_Servlet/filedownload?filename=a.txt">a.txt</a><br> 14 <a href="/Zhan_Web_Servlet/filedownload?filename=a.zip">a.zip</a><br> 15 <a href="/Zhan_Web_Servlet/filedownload?filename=美女.jpg">美女.jpg</a> 16 </body> 17 </html>
Servlet配置文件部分和上篇文章中的一样,对demo包下面的FileDownloadServlet进行修改:
1 package demo; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.URLEncoder; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletOutputStream; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import sun.misc.BASE64Encoder; 15 16 public class FileDownloadServlet extends HttpServlet { 17 18 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 19 //获取要下载文件的名称 20 String fileName = request.getParameter("filename"); 21 22 //解决获得中文参数的乱码 23 fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");//美女.jpg 24 //获得请求头中的User-Agent 25 String agent = request.getHeader("User-Agent"); 26 //根据不同浏览器进行不同的编码 27 String fileNameEncoder = ""; 28 if (agent.contains("MSIE")) { 29 // IE浏览器 30 fileNameEncoder = URLEncoder.encode(fileName, "utf-8"); 31 fileNameEncoder = fileNameEncoder.replace("+", " "); 32 } else if (agent.contains("Firefox")) { 33 // 火狐浏览器 34 BASE64Encoder base64Encoder = new BASE64Encoder(); 35 fileNameEncoder = "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes("utf-8")) + "?="; 37 } else { 38 // 其它浏览器 39 fileNameEncoder = URLEncoder.encode(fileName, "utf-8"); 40 } 41 42 //客户端通过文件的MIME区分下载的文件的类型 43 response.setContentType(this.getServletContext().getMimeType(fileName)); 44 //告诉客户端不要直接解析该文件,而是以附件的形式打开(下载) 客户端默认对名字进行解码 45 response.setHeader("Content-Disposition", "attachment;filename=" + fileNameEncoder); 46 47 //获取要下载文件的绝对路径 48 String realPath = this.getServletContext().getRealPath("download/" + fileName); 49 50 ServletOutputStream out = response.getOutputStream(); 51 InputStream in = new FileInputStream(realPath); 52 int len = 0; 53 byte[] buffer = new byte[1024]; 54 while((len = in.read(buffer)) != -1) { 55 out.write(buffer, 0, len); 56 } 57 in.close(); 58 out.close(); 59 } 60 61 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 62 doGet(request, response); 63 } 64 }
启动服务器,访问download.html,点击美女.jpg即可正常下载。