Response download file of javaweb

 resp.setContentType("text/html;charset=UTF-8");

        //获取下载的地址
        String path = "F:\\java\\javaweb\\response-01\\src\\main\\resources\\home.png";

        System.out.println("下载文件的路径:"+path);

        //下载的文件名

        String filename = path.substring(path.lastIndexOf('\\') + 1);

        System.out.println(filename);

        //设置响应头,和编码
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));


        //获取响应文件的输入流

        FileInputStream in =new FileInputStream(path);

        //创建缓存区
        int len=0;
        byte[] buffer = new byte[1024];

        //获取输出流的对象

        ServletOutputStream out = resp.getOutputStream();

        //将out流写入到buffer中

        while ((len=in.read(buffer))>0){
    
    

            out.write(buffer,0,len);

        }


        //关闭流

        in.close();
        out.close();

Guess you like

Origin blog.csdn.net/qq_42794826/article/details/113823813