首页 > 代码库 > response实现文件下载
response实现文件下载
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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。