• 从服务器指定位置下载文件


    下载文件转换成流,这里说两种流的方式:

    1. 文件流
    2. 字节流

    一,字节流

    String filePath=“/opt/peoject/file/123/pdf”; //这个是你服务上存放文件位置

    方法体,代码如下:

    public byte[] downLoadFile(String filePath) throws Exception {
            byte[] buffer = null;
            try {
                File file = new File(filePath);
                FileInputStream fis = new FileInputStream(filePath);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] b = new byte[1024];
                int n;
                while ((n = fis.read(b)) != -1) {
                    bos.write(b, 0, n);
                }
                fis.close();
                bos.close();
                buffer = bos.toByteArray();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return buffer;
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    后端 controller层

    @PostMapping("/downLoadFile")
    public byte[] downLoadFile(HttpServletRequest request,HttpServletResponse response){
        return  downLoadFile2(response,filePath);
    }
    
    • 1
    • 2
    • 3
    • 4

    前端接收处理、

    参考地址:文件下载

    二,文件流

    public void downLoadFile2(HttpServletResponse response,String filePath) throws Exception {
            File file = new File(filePath);
            //获取文件名称 (例如:123.pdf)
            String fileName=filePath.substring(filePath.lastIndexOf("\\"));
            InputStream inputStream = new FileInputStream(file);
            response.setContentType("application/pdf;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
            inputStream.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    后端controller

    public void downLoadFile(HttpServletRequest request,HttpServletResponse response){
      downLoadFile2(response,filePath);
    }
    
    • 1
    • 2
    • 3

    下载后,浏览器这里会有显示文件
    在这里插入图片描述

  • 相关阅读:
    idna解码nginx重要文件的位置之[SUCTF 2019]Pythonginx
    kubectl 资源管理命令-陈述式
    单区域OSPF配置
    Servlet--Response响应对象
    【Django 03】QuerySet 和 Instance应用
    day2_C++
    AT命令使用和简单介绍
    window.open 打开后全屏
    Golang(go语言)开发环境配置
    Git常用命令
  • 原文地址:https://blog.csdn.net/tt336798/article/details/133144247