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

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

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

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

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

相关推荐
yihuiComeOn24 分钟前
[源码系列:手写Spring] AOP第二节:JDK动态代理 - 当AOP遇见动态代理的浪漫邂逅
java·后端·spring
p***h6431 小时前
JavaScript在Node.js中的异步编程
开发语言·javascript·node.js
Porunarufu1 小时前
Java·关于List
java·开发语言
N***73851 小时前
Vue网络编程详解
前端·javascript·vue.js
靠沿1 小时前
Java数据结构初阶——Collection、List的介绍与ArrayList
java·数据结构·list
程序猿小蒜1 小时前
基于springboot的的学生干部管理系统开发与设计
java·前端·spring boot·后端·spring
q***56382 小时前
Spring容器初始化扩展点:ApplicationContextInitializer
java·后端·spring
q***51892 小时前
SpringCloud系列教程:微服务的未来(十四)网关登录校验、自定义过滤器GlobalFilter、GatawayFilter
java·spring cloud·微服务
go__Ahead2 小时前
【Java】线程池源码解析
java·juc
wyhwust2 小时前
数组----插入一个数到有序数列中
java·数据结构·算法