web下载
编写Servlet启动Tomcat实现在web网页下载文件
public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取写在文件路径 String realPath="D:\\ideaworkplace\\JAVAWEB01\\response\\src\\main\\resource\\jinghua.mp4"; System.out.println("下载路径:"+realPath); //2.下载文件名是什么? String fileName=realPath.substring(realPath.lastIndexOf("\\")+1); //3.设置浏览器支持(Content-Disposition)我们需要的东西,中文文件URLEncoder.encode编码否则可能乱码 resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")); //4.获取下载文件流 FileInputStream in = new FileInputStream(realPath); //5.创建缓冲区 int len=0; byte [] buffer=new byte[1024]; //6.获取OutPutStream对象 ServletOutputStream out=resp.getOutputStream(); //7.将FileOutputStream流写入到buffer缓冲区,使用OutPutStream将缓冲区的数据输出到客户端 while((len=in.read(buffer))>0){ out.write(buffer,0,len); } in.close(); out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
如图所示