码迷,mamicode.com
首页 > 其他好文 > 详细

response实现文件下载

时间:2014-07-02 22:17:15      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   文件   

bubuko.com,布布扣
 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 }
View Code

 

response实现文件下载,布布扣,bubuko.com

response实现文件下载

标签:style   blog   http   java   color   文件   

原文地址:http://www.cnblogs.com/aineko/p/3819020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!