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

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

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

1. 文件流
2. 字节流

一,字节流

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

方法体,代码如下:

java 复制代码
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;
    }

后端 controller层:

javascript 复制代码
@PostMapping("/downLoadFile")
public byte[] downLoadFile(HttpServletRequest request,HttpServletResponse response){
    return  downLoadFile2(response,filePath);
}

前端接收处理、

参考地址:文件下载

二,文件流

javascript 复制代码
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();
    }

后端controller

java 复制代码
public void downLoadFile(HttpServletRequest request,HttpServletResponse response){
  downLoadFile2(response,filePath);
}

下载后,浏览器这里会有显示文件

相关推荐
用户5757303346241 小时前
🐱 从“猫厂”倒闭到“鸭子”横行:一篇让你笑出腹肌的 JS 面向对象指南
javascript
码路飞1 小时前
GPT-5.4 Computer Use 实战:3 步让 AI 操控浏览器帮你干活 🖥️
java·javascript
进击的尘埃1 小时前
Service Worker 离线缓存这事,没你想的那么简单
javascript
进击的尘埃1 小时前
HTTP/3 的多路复用和 QUIC 到底能让页面快多少?聊聊连接迁移和 0-RTT
javascript
Maxkim2 小时前
前端工程化落地指南:pnpm workspace + Monorepo 核心用法与实践
前端·javascript·架构
祈安_2 小时前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法
皮皮林55114 小时前
拒绝写重复代码,试试这套开源的 SpringBoot 组件,效率翻倍~
java·spring boot
小兵张健14 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
codingWhat18 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
Lee川18 小时前
深度拆解:基于面向对象思维的“就地编辑”组件全模块解析
javascript·架构