axios + Spring MVC 上传和下载文件

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完整代码

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue和Spring Boot是一对非常流行的技术组合,用于构建现代Web应用程序。下面是Vue和Spring Boot系统的详细设计: 1. 前端设计 Vue是一种流行的JavaScript框架,可以用于构建现代Web应用程序的用户界面。在Vue中,您可以使用Vue组件来构建应用程序的不同部分。在前端设计中,您需要确定以下内容: - 界面设计:您需要考虑应用程序的用户界面,并确定如何使用Vue组件来构建它。您还需要考虑如何使用Vue路由来管理不同页面之间的导航。 - 数据管理:您需要确定如何使用VueX来管理应用程序的状态。VueX是Vue的状态管理库,可用于管理全局状态和组件之间的通信。 2. 后端设计 Spring Boot是一种流行的Java框架,用于构建Web应用程序的后端。在后端设计中,您需要确定以下内容: - 数据库设计:您需要确定应用程序将使用哪种数据库,并设计数据库模式。您可以使用Spring Data JPA来管理数据库操作。 - REST API设计:您需要确定应用程序将提供哪些REST API,并设计API端点。您可以使用Spring MVC来设计和实现REST API。 3. 集成设计 Vue和Spring Boot是两个独立的应用程序,因此您需要确定如何将它们集成在一起。在集成设计中,您需要考虑以下内容: - 跨域问题:由于Vue和Spring Boot运行在不同的端口上,您需要考虑如何解决跨域问题。您可以在Spring Boot中配置CORS过滤器来解决跨域问题。 - 接口设计:您需要确定Vue应用程序将如何调用Spring Boot提供的REST API。您可以使用Axios库来实现Vue应用程序和Spring Boot之间的通信。 综上所述,Vue和Spring Boot系统的详细设计包括前端设计、后端设计和集成设计。在设计过程中,您需要考虑应用程序的需求和功能,并确定如何使用Vue和Spring Boot来实现它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值