前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/tomcat_day01/downLoad?filename=火影.jpg">图片1</a>
<a href="/tomcat_day01/downLoad?filename=1.avi">视频1</a>
</body>
</html>
后端代码
package cn.wjs.servlet;
import cn.wjs.utils.DownLoadUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 文件下载案例
*/
@WebServlet("/downLoad")
public class DownLoad extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取前台传来的filename
String filename=request.getParameter("filename");
//获取filename的真是路径
// 目标文件夹再web目录下
ServletContext context = this.getServletContext();
String realfile=context.getRealPath("/img/"+filename);
//获取mime类型
String mimeName=context.getMimeType(filename);
//设置相应mime类型
response.setHeader("content-type",mimeName);
//获取不同浏览器通过工具类解决中文文件名乱码
String agent = request.getHeader("user-agent");
filename= DownLoadUtils.getFileName(agent,filename);
//设置资源打开方式
response.setHeader("content-disposition","attachment;filename="+filename);
//获取输入流写入再获取tomcat提供的输出流将流写出
FileInputStream fis=new FileInputStream(new File(realfile));
byte bytes []=new byte[1024*8];
int len=0;
ServletOutputStream out = response.getOutputStream();
while((len=fis.read(bytes))!=-1){
out.write(bytes,0,len);
}
fis.close();
}
}