标签:链接 dog 客户端 index servlet imp type except 第一步
比如这张diqiu.jpg是我们想下载的图片,路径如下图
第一步
index首页一个超链接,地址指向一个servlet的虚拟路径,然后附带一个参数
<a href="/WEB_servlet/download?filename=diqiu.jpg">下载地球.jpg</a>
第二部
新建一个下载的servlet
1 package com.zqf.one; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.ServletOutputStream; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 public class Download extends HttpServlet { 14 15 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 16 //获得下载文件的名称 17 String filename = request.getParameter("filename"); 18 System.out.println(filename); 19 //下载文件类型,客户端通过文件的MIME类型区分 20 response.setContentType(this.getServletContext().getMimeType(filename)); 21 //告诉客户端该文件不是直接解析,而是以附件打开(下载) 22 response.setHeader("Content-Disposition", "attachment;filename="+filename); 23 //获得文件绝对路径 24 String realPath = this.getServletContext().getRealPath("download/"+filename); 25 //获得文件输入流 26 InputStream in=new FileInputStream(realPath); 27 //通过response获得的输出流,用于像客户端些内容 28 ServletOutputStream out=response.getOutputStream(); 29 //文件拷贝的模板代码 30 int len=0; 31 byte[] b=new byte[1024]; 32 while((len=in.read(b))>0) { 33 out.write(b,0,len); 34 } 35 in.close(); 36 out.close(); 37 } 38 39 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 40 doGet(request, response); 41 } 42 }
标签:链接 dog 客户端 index servlet imp type except 第一步
原文地址:https://www.cnblogs.com/breezezqf/p/9380459.html