前后端上传文件、下载文件

本文介绍了如何在React前端利用axios与SpringBoot后端配合,实现文件的下载和上传功能。后端通过读取文件内容为byte[]并设置响应头,前端则处理接收到的二进制数据进行下载或通过FormData上传文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端:React+axios

后端:SpringBoot

下载文件

整体思路

后端读取文件为byte[],返回给前端,前端将byte[]存储为blob并触发点击事件下载

后端

Controller层需要返回给前端ResponseEntity<byte[]>类型

@GetMapping("/catFileStream")
    public ResponseEntity<byte[]> catFileStream() {
        return analysisService.downloadFile(index,type);
    }

业务层的思路是:

  1. 打开文件
  2. 读取文件为byte[]
  3. 设置请求头
    1. 设置返回内容的类型
    2. 设置文件名
  4. 返回ResponseEntity类型
		String filePath = dict + fileName;
        File file = new File(filePath);

        // 读取文件内容到字节数组
        byte[] fileContent = readFileToByteArray(file);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.add("content-disposition","attachment;filename="+file.getName());
        if (file.exists()) {
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .body(fileContent)
                    ;
        } else {
            return ResponseEntity.notFound().build();
        }

前端

使用axios发送GET请求,需要在与header同一级加上responseType:'blob'来表明自己想要的是二进制,blob的意思是大的二进制。
接收:后端返回的数据用res接收。下面的代码可以说是一个固定的流程

  1. 根据返回结果创建blog对象
  2. 根据blog对象创建Url对象
  3. 创建一个看不见的a标签,触发点击事件,即可下载
		const blob = new Blob([res])
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.append(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)

上传

整体思路

前端穿给后端file类型,后端用MultipartFile接收并写文件

前端

用FormData对象包裹File类型对象,防止报什么no boundry错误

const sendFile = (file:File) => {
      console.log(file)
      let formData = new FormData()
      formData.append('file',file)
      uploadFile(formData).then((res) => {
        console.log(res)
      })
    }

使用post发送请求,formData作为请求体,transformRequest部分是去除post请求默认的Content-Type

export function uploadFile(formData:any) {
  return new Promise((resolve) => {
    POST('/smartParse/uploadFile',formData,{
      transformRequest: [function(data, headers) {
        // 去除post请求默认的Content-Type
        delete headers.post['Content-Type']
        return data
      }]
    })
      .then(res => {
        resolve(res)
      })
  })
}

后端

接收如下:

@PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file){
        return analysisService.uploadFile(file);
    }

业务层:
MultipartFile有很多属性接口,但时候就想怎么样就怎么样了。
在这里插入图片描述
注:文件名的获取: String fileName = file.getOriginalFilename();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值