servlet下载文件
文件下载:
下载方式:
1.超链接下载
<a href="/day10/download/day10.txt">下载 day10.txt</a>
若浏览器能解析该资源的mime类型,则打开;若不能接下则下载;
2.编码下载 通过servlet完成
<a href="/day10/download?name=day10.txt">下载 day10.txt</a>
a.设置文件的mime类型
String mimeType=context.getMimeType(文件名)
response.setContentType(mimeType);
b.设置下载头信息 content-disposition
response.setHeader("content-disposition", "attachment;filename="+文件名称);
c.提供流
response.getOutputStream();
扩展:使用commons-io工具类
对拷流:
IOUtils.copy(is,os);
代码展示:
servlet类代码
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
/**
* 文件下载
*/
public class DownServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取下载文件的名称
String filename=request.getParameter("name");
ServletContext context= this.getServletContext();
//文件下载
//1、设置文件的mimeType
String mimeType=context.getMimeType(filename);
response.setContentType(mimeType);
//2、设置下载的头信息
response.setHeader("content-disposition", "attachment;filename"+filename);
//3对拷流
//获取输入流
InputStream is= context.getResourceAsStream("/download/"+filename);
//获取输出流
ServletOutputStream os=response.getOutputStream();
// int len=-1;
// byte[] b= new byte[1024];
// while((len=is.read(b))!=-1) {
// os.write(b,0,len);
// }
IOUtils.copy(is, os);
os.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
download.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/webfour/download?name=1.txt">下载1.txt</a>
<a href="/webfour/download?name=2.txt">下载2.txt</a>
<a href="/webfour/download?name=笔记1.txt">下载笔记1.txt</a>
<a href="/webfour/download?name=作业.doc">下载作业.docx</a>
</body>
</html>
xml文件
<servlet>
<description></description>
<display-name>DownServlet</display-name>
<servlet-name>DownServlet</servlet-name>
<servlet-class>com.feizhu._response_c_download.DownServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
截图
备注:由于个人原因,本博客暂停更新。如有问题可联系本人,本人提供技术指导、学习方向、学习路线。本人微信wlp1156107728(添加注明来意) QQ1156107728(添加注明来意)