多文件上传

要在Vue 2和Spring Boot中实现多文件一次上传,你需要执行以下步骤:

  1. 在Vue 2中创建文件上传组件
    创建一个Vue组件,用于处理文件上传。这个组件可以包含一个或多个文件输入元素,允许用户选择多个文件。
<template>
  <div>
    <input type="file" multiple @change="handleFileUpload">
    <button @click="uploadFiles">上传文件</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedFiles: null
    };
  },
  methods: {
    handleFileUpload(event) {
      this.selectedFiles = event.target.files;
    },
    uploadFiles() {
      const formData = new FormData();
      for(let i = 0; i < this.selectedFiles.length; i++) {
        formData.append('files', this.selectedFiles[i]);
      }
      // 发送文件到后端
      this.$axios.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        console.log(response.data);
      }).catch(error => {
        console.error(error);
      });
    }
  }
}
</script>
  1. 在Spring Boot中创建文件上传接口
    在Spring Boot中创建一个控制器,用于接收文件上传请求,并将文件保存到服务器上。
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("files") MultipartFile[] files) {
        for (MultipartFile file : files) {
            try {
                // 将文件保存到服务器上的指定路径
                file.transferTo(new File("/path/to/save/" + file.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
                return "文件上传失败: " + e.getMessage();
            }
        }
        return "文件上传成功";
    }
}

在这个控制器中,我们使用@PostMapping注解将/upload路径映射到handleFileUpload方法上。这个方法接收一个MultipartFile数组作为参数,其中@RequestParam("files")指定了请求参数的名称为files,这与Vue组件中构建的FormData对象中的键名相对应。

确保Spring Boot应用程序配置了MultipartFile解析器,以正确处理文件上传请求。

这样,当用户选择并上传文件时,Vue组件将文件以FormData形式发送到Spring Boot后端的/upload端点。后端控制器接收到文件后,将其保存到指定的路径,并返回适当的响应给前端。

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[猫玖]

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值