使用Myeclipse 工具
在WebRoot目录下创建一个Download文件夹(new-->folder),以存放 附件(图片,文件...),
具体实现下载功能的代码如下:
- package cn.response;
-
- import java.io.*;
- import java.net.URLEncoder;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- public class Response_download extends HttpServlet {
-
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String path = this.getServletContext().getRealPath("/Download/定南中学.jpg");
- String filename = path.substring(path.lastIndexOf("\\")+1);
-
-
-
- response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
-
- InputStream in = null ;
- OutputStream out = null ;
- try
- {
- in = new FileInputStream(path);
- int len = 0;
- byte buf[] = new byte[1024];
- out = response.getOutputStream();
- while( (len = in.read(buf)) > 0 )
- {
- out.write(buf, 0, len);
- }
- }finally
- {
- if(in!=null)
- {
- try{
- in.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
-
- if(out!=null)
- {
- try{
- out.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- }
-
-
- }
-
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
-
- }
-
- }
注意: try{...} finally{...}
如果 try{...} catch{...} 中没有 catch{...},则必须要加上 finally{...}
finally{...} 一般用来关闭流这些,不管有没有异常,
Response实现文件下载
原文:http://www.cnblogs.com/hoobey/p/5294375.html