天天看点

开发实例:用Vue和Java实现一个批量上传附件的功能

作者:Java技术汇

用Vue和Java实现批量上传附件的基本思路:

Vue端:

  1. 创建一个文件Upload组件,包含一个文件Uploader组件,用于上传附件。
  2. 给Upload组件定义一个props属性,用于接收上传的文件列表。
  3. 在组件的mounted()生命周期方法中,通过ajax发送POST请求,上传附件到服务器,并获取返回结果。
  4. 将返回结果渲染到组件的template中,展示上传结果。

Java端:

  1. 创建一个文件UploadService类,用于处理文件上传请求。
  2. 在upload方法中,使用Java的HttpServletRequest对象获取上传文件列表。
  3. 使用Java的File对象将上传文件保存到服务器指定的目录中。
  4. 返回上传结果给前端页面。
开发实例:用Vue和Java实现一个批量上传附件的功能

以下是Vue和Java实现批量上传附件的代码示例:

Vue端代码:

<template>
  <div>
    <div v-for="(file, index) in fileList" :key="index">
      <div>
        <label>
          <input type="file" :id="`file_${index}`" @change="handleFileChange(index)">
          <span>{{ file.name }}</span>
        </label>
      </div>
      <div>
        <button @click="handleUpload(index)">上传</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    fileList: {
      type: Array,
      required: true
    }
  },
  mounted() {
    this.upload();
  },
  methods: {
    upload() {
      // 上传文件的API endpoint
      const url = 'http://example.com/upload';
      // 上传文件的请求参数
      const formData = new FormData();
      this.fileList.forEach((file, index) => {
        formData.append('file', file);
      });
      // 发送POST请求,上传文件
      axios.post(url, formData).then((res) => {
        console.log(res.data);
        // 处理上传结果
        this.$set(this.fileList, index, res.data.file);
      }).catch((err) => {
        console.log(err);
      });
    },
    handleFileChange(index) {
      const file = this.fileList[index];
      // 将选中的文件名显示在页面上
      this.$set(this.fileList, index, file);
    },
    handleUpload(index) {
      const file = this.fileList[index];
      // 上传文件到服务器
      this.$http.uploadFile(file, '/upload', {
        headers: {'x-token': localStorage.getItem('token')}
      }).then((res) => {
        // 处理上传结果
        console.log(res);
        // 返回上传结果给前端页面
        this.$toast.open({
          message: '上传成功',
          type: 'success'
        });
      }).catch((err) => {
        // 处理上传失败
        console.log(err);
        // 返回上传失败的消息给前端页面
        this.$toast.open({
          message: '上传失败',
          type: 'error'
        });
      });
    }
  }
};
</script>           

Java端代码:

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadService {
  // 处理文件上传请求
  public String upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取上传文件列表
    MultipartFile[] files = request.getFile();
    // 将上传文件保存到服务器指定的目录中
    for (MultipartFile file : files) {
      File dir = new File("/upload/");
      if (!dir.exists()) {
        dir.mkdirs();
      }
      file.transferTo(dir);
    }
    return "上传成功";
  }
}           

继续阅读