前端:React+axios
后端:SpringBoot
下载文件
整体思路
后端读取文件为byte[],返回给前端,前端将byte[]存储为blob并触发点击事件下载
后端
Controller层需要返回给前端ResponseEntity<byte[]>类型
@GetMapping("/catFileStream")
public ResponseEntity<byte[]> catFileStream() {
return analysisService.downloadFile(index,type);
}
业务层的思路是:
- 打开文件
- 读取文件为byte[]
- 设置请求头
- 设置返回内容的类型
- 设置文件名
- 返回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接收。下面的代码可以说是一个固定的流程
- 根据返回结果创建blog对象
- 根据blog对象创建Url对象
- 创建一个看不见的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();