servlet技术之下载文件演示(DownloadServlet.class)
文件是指把服务器端文件发送到客户端,Servlet能够向客户端发送任意格式的文件数据,例程的DownloadServlet类先获得请求参数filename,该参数代表客户端请求下载的文件名,DownloadServlet先通过ServletContext的getResourceAsStream()方法得到一个用于读取相应文件的输入流,再调用一个用于输出响应正文的输出流。DownloadServlet然后通过输入流读取文件数据,在通过输出流把文件中的数据输出到客户端。
Web.xml
<servlet> <servlet-name>Down</servlet-name> <servlet-class>com.demo.servlet.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Down</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping>
|
DownloadServlet.class
package com.demo.servlet;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
/** * Created by 谭雪娇 on 2017/4/7. */ public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request , HttpServletResponse response)throws ServletException ,IOException{ OutputStream out;//输出响应正文的输出流 InputStream in;//输出响应正文的输入流 String filename=request.getParameter("filename"); if(filename==null){ out=response.getOutputStream(); out.write("please input filename".getBytes()); out.close(); return ; } //获得读取本地文件的输入流 in=getServletContext().getResourceAsStream(filename); int length=in.available(); //设置MIME类型的响应正文 response.setContentType("application/force-download"); response.setHeader("content-length",String.valueOf(length)); response.setHeader("content-Disposition","attachment;filename=\" "+filename+" \" "); /*把本地文件中的数据发送给客户*/ out=response.getOutputStream(); int byteRead=0; byte[] buffer=new byte[512]; if((byteRead=in.read(buffer))!=-1){ out.write(buffer,0,byteRead); } in.close(); out.close(); } }
|
DownloadServlet把响应正文的类型设置为”application/force-download”,当浏览器读取这种MIME类型的响应正文时会以下载的方式来处理响应正文,
在web.xml中为DownloadServlet映射的URL为”/download”,在浏览器输入http://localhost:8080/download/filename=fromserver.rar,浏览器端会输出如图所示结果