1 package cn.itcast.response; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 import java.io.PrintWriter; 8 import java.io.UnsupportedEncodingException; 9 import java.net.URLEncoder; 10 11 import javax.servlet.ServletException; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 public class ResponseDemo extends HttpServlet { 17 18 public void doGet(HttpServletRequest request, HttpServletResponse response) 19 throws ServletException, IOException { 20 21 String path = this.getServletContext().getRealPath("/download/日本妞.jpg"); 22 String filename = path.substring(path.lastIndexOf("\\") + 1); 23 24 //如果下载文件是中文文件,则文件名需要经过URL编码 25 response.setHeader("content-disposition", "attachment;filename=" 26 + URLEncoder.encode(filename,"UTF-8")); 27 28 InputStream in = null; 29 OutputStream out = null; 30 31 in = new FileInputStream(path); 32 int len = 0; 33 byte buffer[] = new byte[1024]; 34 35 out = response.getOutputStream(); 36 while ((len = in.read(buffer)) > 0) { 37 out.write(buffer, 0, len); 38 } 39 40 in.close(); 41 out.close(); 42 43 } 44 45 public void doPost(HttpServletRequest request, HttpServletResponse response) 46 throws ServletException, IOException { 47 48 } 49 50 }
response实现文件下载
时间: 2024-10-10 18:06:10