简单文件下载,servlet+jsp

来源:互联网 发布:sql distinct 所有字段 编辑:程序博客网 时间:2024/05/22 04:44

服务器端

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubString filename=request.getParameter("filename");System.out.println(filename);String path=getServletContext().getRealPath("/");String folder="upload/";String z=path+folder+filename;response.setHeader("Content-Disposition", "attachment;filename="+filename+"");//download 必须设置File file=new File(z);InputStream is=new FileInputStream(file);OutputStream os=response.getOutputStream();byte[] b=new byte[1024];int len=0;while((len=is.read(b))!=-1){               os.write(b, 0, len);}os.flush();os.close();is.close();System.out.println("download success");}

jsp

<a href="DownLoadSevlet?filename=${refFile}" >download</a>  //retFile是后台request传来的文件名,如xxxx.mp4,或者自己写一个upload下存在的文件名称

web.xml

<servlet-name>DownLoadSevlet</servlet-name><servlet-class>test.DownLoadSevlet</servlet-class></servlet><servlet-mapping><servlet-name>DownLoadSevlet</servlet-name>   <url-pattern>/DownLoadSevlet</url-pattern>    </servlet-mapping>


0 0
原创粉丝点击