SpringBoot+vue实现文件上传

话不多说,直接上代码:

vue前端:

<template>
<el-upload style="display: inline;"
           class="upload-ckd"
           ref="upload"
           action="doUpload"
           :limit="1"
           :before-upload="beforeUpload">
  <el-button slot="trigger" type="primary" style="margin-left: 10px;">上传</el-button>
</el-upload>
</template>
<script>
beforeUpload(file){
  if(isEmpty(file.name)){
    this.$message.warning('请选择要上传的文件!')
    return false
  }
  this.files = file;
  const extension = file.name.split('.')[1] === 'xls'
  const extension2 = file.name.split('.')[1] === 'xlsx'
  const extension3 = file.name.split('.')[1] === 'XLS'
  const extension4 = file.name.split('.')[1] === 'XLSX'
  const isMt10M = file.size / 1024 / 1024 >10
  if (!extension && !extension2 && !extension3 && !extension4) {
    this.$message.warning('上传模板只能是 xls、xlsx格式!')
    return
  }
  if (isMt10M) {
    this.$message.warning('上传模板大小不能超过 10MB!')
    return
  }
  this.fileName = file.name;
  setTimeout(() => {
    this.submitUpload();
  },500);
  return false // 返回false不会自动上传
},
submitUpload() {
  let fileFormData = new FormData();
  fileFormData.append('file', this.files, this.fileName);//filename是键,file是值,就是要传的文件,test.zip是要传的文件名
  this.commonPost({
    url: HMD_UPLOADCKD,
    params: fileFormData,
    requestBody: true
  }).then((data) =>{
    if(data){
      this.$message.success("上传成功");
      this.loadData();
    }
  },(error) => {
    console.log(error);
    this.$message.error("上传失败");
    this.loadData();
  })
}
<script>

后端:

注意点:

1、springBoot的配置文件添加:

spring.servlet.multipart.max-file-size=10Mb
spring.servlet.multipart.max-request-size=-1
@PostMapping (value = "ckd/uploadCkdExecl")
public Object uploadCkdExecl(@RequestParam("file") MultipartFile file, HttpServletRequest request)throws Exception {
    if (file.isEmpty()) {
        throw new BusinessException("上传文件不能为空");
    }
    String fileName=file.getOriginalFilename().toLowerCase();
    if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
        throw new BusinessException("请上传Excel文件");
    }
    //操作人
    String operator=request.getAttribute(StrUtil.USER_WORKNUMBER).toString();
    xxxService.saveUploadCkdExecl(file,operator);
    return true;
}

 

3、附:备份文件:

/**
 * 备份上传文件
 * 
 * @param file
 *            文件
 *            文件名
 * @param BackFilePath
 *            文件备份路径
 * @return 返回备份文件名
 */
public static String backImportFile(MultipartFile file, String BackFilePath)throws Exception{
    StringBuilder sb = new StringBuilder();
    try {
        sb.append(BackFilePath).append("/").append(TimeUtil.getCurTimeToFormat("yyyyMMdd"));
        //判断路径是否存在,不存在则创建
        if (!Files.isWritable(Paths.get(sb.toString()))) {
            try {
                Files.createDirectories(Paths.get(sb.toString()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sb.append("/")
                .append(TimeUtil.getCurTimeToFormat("HHmmss"))
                .append("-")
                .append(file.getOriginalFilename());

        byte[] bytes = file.getBytes();
        Path path = Paths.get(sb.toString());
        //文件写入指定路径
        Files.write(path, bytes);
    } catch (IOException e) {
        throw new Exception("备份文件失败");
    }
    return sb.toString().substring(sb.toString().lastIndexOf("/")+1);
}
<h3>回答1:</h3><br/>如何实现SpringBoot+Vue文件上传文件上传涉及前端和后端两个方面的实现。 前端的Vue代码: 1. 定义上传文件的模板: ``` <template> <div> <input type="file" @change="handleFileUpload" ref="fileUpload"> <button @click="submitFile">上传文件</button> </div> </template> ``` 2. 在Vue的methods中添加上传文件的方法: ``` methods: { handleFileUpload () { this.file = this.$refs.fileUpload.files[0] }, submitFile () { let formData = new FormData() formData.append('file', this.file) axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log(response.data) }) } } ``` 这个方法中,我们通过FormData对象来将文件对象上传到服务器端。需要注意的是,在axios请求中,我们需要指定Content-Type为multipart/form-data,以便后端能够正确地解析上传的文件。 后端的SpringBoot代码: 1. 配置文件上传的Multipart配置 在application.properties文件中添加以下配置: ``` spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` 这个配置指定了上传文件的大小限制,例如,上限设置为10MB。 2. 添加文件上传的Controller ``` @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 将上传的文件保存到指定路径下 String filePath = "C:/uploads/" + file.getOriginalFilename(); file.transferTo(new File(filePath)); return "文件上传成功"; } catch (IOException e) { e.printStackTrace(); return "文件上传失败"; } } } ``` 这个Controller中,通过@RequestParam注解来指定上传的文件参数名,再通过MultipartFile来获取上传的文件。最后,将文件保存到指定的路径下。需要注意的是,保存路径需要在业务中合理设置。 至此,SpringBoot+Vue文件上传实现就完成了。 <h3>回答2:</h3><br/>Spring Boot是一个广受欢迎的Java开发框架,Vue是一款流行的前端开发框架,他们之间的结合可以为用户提供高效、易用的Web应用程序。在其中,文件上传是Web应用程序的必备功能之一。Spring Boot和Vue的结合可使文件上传实现更加轻松快捷。 首先,需要在前端部分使用Vue来创建一个简单的文件上传组件,该组件可以实现文件选择、文件上传以及进度条的显示等功能。可以使用vue-file-upload或者其他类似的第三方库来实现文件上传功能,同时需要在该组件中设置上传API的路径和上传的文件名。 然后,需要在后端部分使用Spring Boot来处理上传的文件。Spring Boot提供了丰富的文件处理工具和API,可以轻松地实现文件上传。可以使用Spring Boot的MultipartResolver来解析文件上传请求,同时可以使用MultipartFile类来获取上传的文件对象。 接着,需要在Spring Boot的Controller中创建一个上传接口用于处理文件上传请求。该接口需要使用@RequestParam注解来获取上传的文件对象,并使用MultipartFile类来处理文件上传。同时,还需要设置上传文件的路径,并将上传成功后的文件路径返回到前端。 最后,需要在前端页面使用Vue来处理上传结果。根据上传返回的结果,可以在页面上显示上传成功或者上传失败的提示信息。同时,还可以使用Vue实现进度条的动态更新,用以提醒用户当前的上传状态。 总的来说,Spring Boot和Vue的结合可以实现快速、高效的文件上传功能。借助两个框架提供的强大工具和API,开发者可以轻松地实现文件上传功能,提高Web应用程序的可靠性和用户体验。 <h3>回答3:</h3><br/>SpringBoot是一个基于Spring框架的快速开发微服务的工具,它简化了Spring框架的配置,使开发者可以快速上手。Vue是一款流行的前端框架,它具有高效的组件化开发和数据双向绑定等优点。在实现文件上传功能时,可以结合使用SpringBootVue实现。 首先,需要在SpringBoot的依赖管理文件pom.xml中添加对spring-boot-starter-web和spring-boot-starter-test的引用: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> ``` 然后,在SpringBoot的配置文件application.properties中添加文件上传的配置: ``` spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=200MB spring.servlet.multipart.max-request-size=215MB ``` 接下来,在SpringBoot的Controller中编写文件上传接口: ``` @RestController @RequestMapping("/api") @CrossOrigin(origins = "*", maxAge = 3600) public class UploadController { @PostMapping("/upload") public ResponseResult upload(@RequestParam("file") MultipartFile file) { // 处理文件上传业务逻辑 } } ``` 在Vue的组件中,可以使用vue-axios实现文件上传: ``` <template> <div> <input type="file" @change="uploadFile" /> </div> </template> <script> import axios from 'axios'; export default { data() { return { file: null } }, methods: { uploadFile() { let formData = new FormData(); formData.append('file', this.file); axios.post('http://localhost:8080/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(error => { console.log(error); }) } } } </script> ``` 其中,formData为提交的表单数据,append方法将文件对象添加到表单中。axios.post方法发送POST请求,在请求头中设置Content-Type为multipart/form-data。 总体来说,使用SpringBootVue实现文件上传功能比较简单。通过配置SpringBoot文件上传参数和编写文件上传接口,配合Vue文件上传组件,即可实现文件的上传功能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值