文件下载
1、超链接下载(某些不适用)
某些格式的文件可以直接下载,某些就直接在浏览器打开了,根据文件的mime类型决定的,如果说浏览器不能识别的mime类型,那么就提示下载如果可以识别,就直接打开
2、编码下载
1、设置文件的mime类型
2、设置下载头信息
3、流操作
例如:
@WebServlet(value = "/fileDownloadServlet",name = "FileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取文件名
String name = request.getParameter("name");
//2、文件真实路径
String filepath = "E:\\file\\"+name;
//3、创建输入流
FileInputStream in = new FileInputStream(filepath);
//4、设置response的响应头 ServletContext
ServletContext context = getServletContext();
//获取文件的mime类型
String mimeType = context.getMimeType(name);
response.setHeader("content-type",mimeType);
//解决中文乱码:
//获取user-agent
String agent = request.getHeader("user-agent");
String fileName = DownLoadUtils.getFileName(agent, name);
//设置下载头信息
response.setHeader("content-disposition", "attachment; filename="+fileName);
//流操作
ServletOutputStream out = response.getOutputStream();
byte[] b = new byte[1024 * 10];
int len = 0;
while((len = in.read(b)) != -1){
out.write(b, 0, len);
}
out.close();
in.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response );
}
}