前后端实现文件流的传输,实现文件下载功能

1、后端代码
参数response 是文件流传输必须的,
然后chatFileParam是业务需要用来获取服务器文件的,你们可以不看,不写

  /**
     * 页面下载文件
     * @param response 
     * @param chatFileParam  
     */
	 @ApiOperation(value = "页面下载文件")
    @PostMapping("downFileForWeb")
    public void downFileForWeb(HttpServletResponse response, @RequestBody ChatFileParam chatFileParam) {
        try {
        	// 获取本地文件  你们可以通过FileInputStream(文件路径)获取File对象
            if (StringUtils.isEmpty(chatFileParam.getUrlStr())){
                throw new IllegalArgumentException("文件路径不存在!");
            }
            File file = cosFileService.download(chatFileParam.getUrlStr());
            // 下面是获取文件流并发送给前端,response会将文件流发送给前端
            response.setCharacterEncoding("UTF-8");
            if (file == null || !file.exists()){
                throw new IllegalArgumentException("文件不存在!");
            }
            String simpleName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
            String newFileName = new String(simpleName.getBytes(), StandardCharsets.UTF_8);
            response.setHeader("Content-disposition", "attachment;filename=" + newFileName);
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(
                    response.getOutputStream());
            byte[] buffer = new byte[1024];
            int length;
            while ((length = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
            bis.close();
            bos.close();
        } catch (InterruptedException | IOException | IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}

2、前端点击后下载文件
在这里插入图片描述
代码
首先是访问后台请求

export function downFile(params){
  return request({
    method: 'post',
    url: '/tfapp/chatFile/downFileForWeb',
    responseType:'blob',//接收的文件流对象,很重要
    data: params //业务需要传递的参数
  });
}

页面点击事件调用

import {downFile} from "@/api/chat";
downFile(fileName) {
			console.log('文件名',fileName)
            // 解析文件名
            content.split("\">")
            const result = await downFile(params);
            let url = window.URL.createObjectURL(result)
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
} 		

调用downFile请求时,返回的时Blob对象,如下图所示
在这里插入图片描述

3、效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值