天天看點

開發執行個體:用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 "上傳成功";
  }
}           

繼續閱讀