axios + Spring MVC 上传和下载文件

本文详细介绍了文件上传和下载的前后端实现方法,包括使用FormData进行文件上传的前端操作,以及后端如何将文件写入本地磁盘;同时,阐述了通过Blob实现文件下载的前端处理方式,和后端如何响应前端的下载请求,提供了一个完整的文件上传与下载的技术方案。

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

1. 上传

1.1 前端

export function importFile (param) {
  return axios.post('/importFile', param)
}

获取文件,用FormData包装,调用接口

const element = document.getElementById('fileToUpload')
const files = element.files
const formData = new FormData()
const file = element.files[0]
formData.append('file', file)
importFile(formData).then(res => {
// ...
})

1.2 后端

写入本地磁盘

public void importFile(@RequestParam("file") MultipartFile file) {
	LocalDateTime now = LocalDateTime.now();
    String uploadPath = new StringBuilder()
            .append(now.getYear()).append(File.separator)
            .append(now.getMonthValue()).append(File.separator)
            .append(now.getDayOfMonth()).append(File.separator)
            .append(now.getHour()).append(File.separator)
            .append(now.getMinute()).append(File.separator)
            .append( now.getSecond()).append(File.separator)
            .toString();

    File dictionary = new File(localUploadDir + uploadPath);
    if (!dictionary.exists()){
        dictionary.mkdirs();
    }

    String fileName = file.getOriginalFilename();
    String des = localUploadDir + uploadPath + fileName;
    try (
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(des));
            InputStream inputStream = file.getInputStream();
    ) {
        if (!file.isEmpty()) {
            int len;
            byte[] bytes = new byte[1024 * 1024];
            while ((len = inputStream.read(bytes)) > 0){
                bufferedOutputStream.write(bytes,0, len);
            }
        }
    }catch (Exception e){
        e.printStackTrace();
        logger.error("文件 {} 写入异常", fileName);
    }
}

2. 下载

2.1 前端

修改返回类型

export function downloadFile (id) {
  return axios.get('/downloadFile?id=' + id,
    {
      responseType: 'arraybuffer'
    }
  )
}

通过Blob下载

downloadFile(id).then(res => {
  this.getDownloadFileResult (res, fileName)
})

getDownloadFileResult (res, fileName) {
  const blob = new Blob([res])
  const downloadLink = document.createElement('a')
  // 创建下载的链接
  const href = window.URL.createObjectURL(blob)
  downloadLink.href = href
  downloadLink.download = fileName
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
  // 释放掉Blob对象
  window.URL.revokeObjectURL(href)
}

2.2 后端

public ResponseEntity<byte[]> downloadFile(@RequestParam("id") Integer id) {
	String filePath = localUploadDir + "2020\2\17\17\23\50\测试.xlsx";
	String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
	
	HttpHeaders headers = new HttpHeaders();
	headers.setContentDispositionFormData("attachment", new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	
	byte[] bytes = null;
	try {
	    bytes = FileUtils.readFileToByteArray(new File(filePath));
	} catch (IOException e) {
	    e.printStackTrace();
	    logger.error("文件 {} 读取异常", fileName);
	}
	return new ResponseEntity<>(bytes ,headers, HttpStatus.CREATED);
}

参考:
使用axios上传文件、下载(导出)文件
vue axios get和post请求下载文件,后台springmvc完整代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值