response之 servlet下载

来源:互联网 发布:行政学院网络教学平台 编辑:程序博客网 时间:2024/05/05 09:13
package com.servlet;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.OutputStream;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.io.InputStream;public class servletDownload extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse response)throws ServletException,IOException {test1(response);}private void test1(HttpServletResponse response)throws FileNotFoundException, IOException {String path=this.getServletContext().getRealPath("/down/tu.jpg");/*关于String filename=path.substring(path.lastIndexOf("\\")+1);详细解释:首先先看我们获取的路径 path打印结果是:文件路径是:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ceshi\down\tu.jpg第二  lastIndexOf:返回指定子字符串在此字符串中最右边出现处的索引。看下此索引是从0开始的,打印结果是:最右边出现的索引是:87字符串长度是:93 "\\"我就不说啦,就是为了获取\,要加个转义为什么加1呢,看apiast IndexOf:返回指定子字符串在此字符串中最右边出现处的索引。也就是说此时返回的字符串在右边出现的索引,也就是"\"的索引位置,我们要是后面的名字,所以加1int u=path.length();int s=path.lastIndexOf("\\")+1;System.out.println("字符串长度是:"+u);System.out.println("最右边出现的索引是:"+s);filename 最后要获取的名字是:tu.jpg*/String filename=path.substring(path.lastIndexOf("\\")+1);java.io.InputStream in=null;OutputStream out=null;/*content-disposition: * 当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。 * Content-Disposition中指定的类型是文件的扩展名,并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的, * 点保存后,文件以filename的值命名,保存类型以Content中设置的为准。 * attachment: * 指定类型为下载 * URLEncoder.encode(filename,"utf-8"): * 发送请求,下载中文名字的文件,需要转码 *  *  */response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));try {in=new FileInputStream(path);int len=0;byte buffer[]=new byte[1024];out=response.getOutputStream();while((len=in.read(buffer))>0){out.write(buffer,0,len);}}finally{if(in!=null){try{in.close();}catch(Exception e){e.printStackTrace();}}}}}

response.setHeader()的用法: http://blog.csdn.net/fanyuna/article/details/5568089


0 0
原创粉丝点击