本文实例为大家分享了Jsp实现文件下载功能的3种方法,供大家参考,具体内容如下
第一种、采用转发的方式:
package cn.jbit.download.servlet; import java.io.IOException; import javax.servlet.Requestdispatcher; import javax.servlet.servletexception; import javax.servlet.http.httpServlet; import javax.servlet.http.httpServletRequest; import javax.servlet.http.httpServletResponse; public class DownloadServlet extends httpServlet { private static final long serialVersionUID = 6765085208899952414L; public voID doGet(httpServletRequest request,httpServletResponse response) throws servletexception,IOException { doPost(request,response); } public voID doPost(httpServletRequest request,IOException { String filedownload = "/upload/1/10213.jpg";//即将下载的文件的相对路径 String filedisplay = "10213.jpg";//下载文件时显示的文件保存名称 response.setContentType("application/x-download");//设置为下载application/x-download //response.setContentType("application/x-msdownload");//设置为下载application/x-msdownload //response.setContentType("application/octet-stream");//设置为下载application/octet-stream response.addheader("Content-disposition","attachment;filename=" + filedisplay); try { Requestdispatcher rd = request.getRequestdispatcher(filedownload); if(rd != null) { rd.forward(request,response); } response.flushBuffer(); } catch (Exception e) { e.printstacktrace(); } } }
二、通过输出流的方式:
package cn.jbit.download.servlet; import java.io.BufferedinputStream; import java.io.bufferedoutputstream; import java.io.file; import java.io.fileinputStream; import java.io.IOException; import java.io.inputStream; import java.io.OutputStream; import javax.servlet.servletexception; import javax.servlet.http.httpServlet; import javax.servlet.http.httpServletRequest; import javax.servlet.http.httpServletResponse; public class DownloadOfIOServlet extends httpServlet { public voID doGet(httpServletRequest request,response); } public voID doPost(httpServletRequest request,IOException { String basePath = request.getSession().getServletContext().getRealPath("/upload"); String filedisplay = "helloworld.jpg"; String filedownload = basePath + file.separator + "helloworld.jpg"; response.setContentType("applicaiton/x-download"); response.addheader("Content-disposition","attachment;filename="+filedisplay); inputStream is = null; OutputStream os = null; BufferedinputStream bis = null; bufferedoutputstream bos = null; is = new fileinputStream(new file(filedownload)); bis = new BufferedinputStream(is); os = response.getoutputStream(); bos = new bufferedoutputstream(os); byte[] b = new byte[1024]; int len = 0; while((len = bis.read(b)) != -1){ bos.write(b,len); } bis.close(); is.close(); bos.close(); os.close(); } }
第三种、通过超链接的方式(注意不推荐,因为会暴露下载文件的位置)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的jsp文件下载功能实现代码全部内容,希望文章能够帮你解决jsp文件下载功能实现代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)