package com.aojie.web.download;
import com.aojie.web.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.FileInputStream;
import java.io.IOException;
/**
* @author aojie
* @fuction
* @create 2020-04-20 21:45
*/
@WebServlet("/servletDownload")
public class ServletDownload extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求参数
String filename = request.getParameter("filename");
//使用字节输入流把文件加载进内存
//找到文件服务器路径
//使用字节流关联
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/imge/" + filename);
FileInputStream fis=new FileInputStream(realPath);
String mimeType = servletContext.getMimeType(filename);
//解决中文文件名问题
String header = request.getHeader("user-agent");
filename = DownLoadUtils.getFileName(header, filename);
//设置response响应头类型和打开方式
response.setHeader("content-type",mimeType);
response.setHeader("content-disposition","attachment;filename="+filename);
//将输入流写出到输出流
ServletOutputStream outputStream = response.getOutputStream();
byte[] buff=new byte[1024];
int len=0;
while((len=fis.read(buff))!=-1){
outputStream.write(buff,0,len);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
2020.04.20 超链接文件下载案例
猜你喜欢
转载自www.cnblogs.com/aojie/p/12741134.html
今日推荐
周排行