文件下载
response实现的主要分两种方法
方法一
超链接下载:
分析: 示例 <a href =“../day/download/1.txt”> 下载1.txt</a>
若浏览器能识别文件的mime类型,则会打开;不能识别则会直接下载
方法二
编码下载:(重点)
public class DownloadServlet 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", "attchment;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();
}
}