基本知识
想要从浏览器下载文件到本机中,首先要将服务器中的文件加载进内存,然后设置响应头,最后再将文件写出到本地硬盘
相应头的设置:
- Content-Type:服务器告诉客户端本次响应体数据格式以及编码格式
- Content-disposition:服务器告诉客户端以什么格式打开响应体数据
String mimeType = servletContext.getMimeType(filename);
response.setHeader("content-type",mimeType);
response.setHeader("content-disposition","attachment;filename="+filename);
下载页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>下载</title>
</head>
<body>
<a href="/Download/downloadServlet?filename=31.jpg"> 下载图片</a>
<a href="/Download/downloadServlet?filename=tomcat.avi"> 下载视频</a>
</body>
</html>
服务器响应端
@WebServlet("/downloadServlet")
public class downloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.setHeader("content-type","");
//1.获取文件名称
String filename = request.getParameter("filename");
//2.加载文件进内存
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/img/" + filename);
FileInputStream is = new FileInputStream(realPath);
//3.设置响应头
String mimeType = servletContext.getMimeType(filename);
response.setHeader("content-type",mimeType);
response.setHeader("content-disposition","attachment;filename="+filename);
//4.写出数据
ServletOutputStream sos = response.getOutputStream();
byte[] buff= new byte[1024];
int len=0;
while ((len=is.read(buff)) !=-1){
sos.write(buff,0,len);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
效果展示
异常处理:
参考状态码信息进行修改
1. 1xx:服务器就收客户端消息,但没有接受完成,等待一段时间后,发送1xx多状态码
2. 2xx:成功。代表:200
3. 3xx:重定向。代表:302(重定向),304(访问缓存)
4. 4xx:客户端错误。 404(请求路径没有对应的资源) 405:请求方式没有对应的doXxx方法
5. 5xx:服务器端错误。代表:500(服务器内部出现异常)