@WebServlet("/DownloadServlet02")
public class DownloadServlet02 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取文件名称
String filename = request.getParameter("filename");
//获取ServletContext域对象
ServletContext servletContext = this.getServletContext();
//获取文件的路径
String realPath = servletContext.getRealPath("/img/" + filename);
//输入流读取文件
FileInputStream fis = new FileInputStream(realPath);
//获取文件的类型
String mimeType = servletContext.getMimeType(filename);
//设置content-type
response.setHeader("content-type",mimeType);
//防乱码
String agent = request.getHeader("user-agent");
filename = DownLoadUtils.getFileName(agent, filename);
//设置将文件作为附件加载
response.setHeader("content-disposition","attachment;filename="+filename);
//写出文件
ServletOutputStream ops = response.getOutputStream();
byte[] buff = new byte[1024*5];
int len=0;
while((len=fis.read(buff))!=-1){
ops.write(buff,0,len);
}
fis.close();
} |
|