一:下载就是向客户端响应字节数据而不是html字符数据
把一个文件变成字节数组,使用response.getOutputStream()来响应浏览器
二:下载的要求
简单来概括就是——两头一流
Content-Type:传递给客户端的是什么MIME类型,例如:image/pjpeg图片类型
Content-Disposition:(内容处置)默认值是inline,表示在浏览器窗口打开!attachment;filename=xxx,xxx就是你下载的文件名称
流:要下载的数据
String filename = "G:/百度云/软件设计师视频(考试用)/第八节 寻址方式.avi"; String contentType = this.getServletContext().getMimeType(filename); String contentDispositon = "attachment;filename=a.avi"; FileInputStream inputStream = new FileInputStream(filename);
三:下载的细节
下载框中中文名称会乱码
大部分浏览器使用的URL编码,fireFox使用的是Base64编码
通用方案:
filename = new String(filename.getBytes("GBK"),"ISO-8859-1");
四:源码
package servlet; import java.io.FileInputStream; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.net.URLEncoder; import sun.misc.BASE64Encoder; /** * Created by YuWenHui on 2017/4/13 0013. */ public class DownloadServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { /** * 两个头一个流 */ String filename = "G:/百度云/软件设计师视频(考试用)/第八节 寻址方式.avi"; int index = filename.lastIndexOf("/"); // 不能直接对filename进行处理,因为后面需要对filename进行加载 String filename1 = filename; if (index != -1){ filename1= filename.substring(index+1); } String frameName = filenameEncoding(filename1,request); String contentType = this.getServletContext().getMimeType(filename); String contentDispositon = "attachment;filename="+frameName; FileInputStream inputStream = new FileInputStream(filename); // 设置头 response.setHeader("Content-Type",contentType); response.setHeader("Content-Disposition",contentDispositon); // 获取绑定了的响应端流 ServletOutputStream outputStream = response.getOutputStream(); org.apache.commons.io.IOUtils.copy(inputStream,outputStream); inputStream.close(); } // 用来对下载的文件名称进行编码的! public static String filenameEncoding(String filename, HttpServletRequest request) throws IOException { String agent = request.getHeader("User-Agent"); //获取浏览器 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; } }