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

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

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

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);
}

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

相关推荐
北友舰长6 分钟前
基于Springboot+thymeleaf图书管理系统的设计与实现【Java毕业设计·安装调试·代码讲解】
java·spring boot·mysql·课程设计·图书管理·b/s·图书
陈文锦丫7 小时前
MQ的学习
java·开发语言
乌暮7 小时前
JavaEE初阶---线程安全问题
java·java-ee
爱笑的眼睛117 小时前
GraphQL:从数据查询到应用架构的范式演进
java·人工智能·python·ai
Seven978 小时前
剑指offer-52、正则表达式匹配
java
信看8 小时前
NMEA-GNSS-RTK 定位html小工具
前端·javascript·html
代码or搬砖8 小时前
RBAC(权限认证)小例子
java·数据库·spring boot
青蛙大侠公主8 小时前
Thread及其相关类
java·开发语言
爱吃大芒果8 小时前
Flutter 主题与深色模式:全局样式统一与动态切换
开发语言·javascript·flutter·ecmascript·gitcode