package com.itcast.servlet; import com.itcast.utils.DownLoadUtils; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * 1.点击服务器连接,提交服务器参数,下载的文件名 * 2.获取文件名,找到文件的真是路径; * 文件中下载:头信息设置 * 1.设置文件的媒体路径。 * 2.设置文件附件形式。 */ public class Servlet01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.接受参数 String filename = req.getParameter("filename"); //2.设置Context-Type ServletContext servletContext = getServletContext(); String mimeType = servletContext.getMimeType(filename); resp.setHeader("Context-Type", mimeType); //3.将文件名进行编码,返回给浏览器 String newFilename = DownLoadUtils.encodeFileName(req, filename); //4.设置Content-Disposition头,只有设置这个参数,浏览器才会将文件作为下载目标下载 resp.setHeader("Content-Disposition", "attachment;filename=" + newFilename); //4.设置文件的InPutStream String realPath = servletContext.getRealPath("/download/" + filename); InputStream is = new FileInputStream(realPath); //5.获取输出流 ServletOutputStream os = resp.getOutputStream(); int len = 0; byte[] b = new byte[1024]; while ((len = is.read(b)) != -1) { os.write(b, 0, len); } is.close(); os.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
//转换工具类
package com.itcast.utils; import sun.misc.BASE64Encoder; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class DownLoadUtils { public static String encodeFileName(HttpServletRequest request, String fileName) { String name = ""; String agent = request.getHeader("User-Agent"); System.out.println(agent); try { if (agent.contains("Firefox")) { BASE64Encoder base64Encoder = new BASE64Encoder(); name = "=?UTF-8?B?" + new String(base64Encoder.encode(fileName.getBytes("UTF-8"))) + "?="; } else { name = URLEncoder.encode(fileName, "UTF-8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //System.out.println(name); return name; } }