• Servlet的response实现 文件下载


    文件下载

    public class FileServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             //获取文件路径
            String realPath = "D:\\javaweb-02-maven\\servlet-01\\src\\main\\resource\\img.png";
            //D:\javaweb-02-maven\servlet-01\src\main\resource\img.png
            System.out.println("下载路径"+realPath);
            //下载的文件名
            String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
           //让浏览器能支持所下载的的东西
            resp.setHeader("Content-disposition","attachment;filename"+filename);
           //获得下载文件的输入流
            FileInputStream fileInputStream = new FileInputStream(realPath);
            //创建缓冲区
            int len=0;
            byte[] buffer=new byte[1024];
            //获得OutputStream流
            ServletOutputStream outputStream = resp.getOutputStream();
            //将FileInputStream写到缓冲区
            while((len=fileInputStream.read(buffer))>0){
                outputStream.write(buffer,0,len);
            }
            //关闭流保证安全
               fileInputStream.close();;
               outputStream.close();
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp);
        }
    }
    ```
    `
  • 相关阅读:
    supervisor启动错误解决(二)
    删除文件某行
    离线安装
    docker中/var/lib/docker目录迁移
    if else 使用
    Django views函数添加装饰器
    Netty4
    Fast DFS(二)
    Fast DFS(一)
    SpringBoot和app之间跨域问题
  • 原文地址:https://www.cnblogs.com/xiaxiaopi/p/14389651.html
Copyright © 2020-2023  润新知