1. 程式人生 > 其它 >前端向後端傳檔案

前端向後端傳檔案

前端使用VUE

後端使用SpringBoot

前端

獲取檔案:

<el-upload
              action=""
              accept="video/*"
              :on-change="onUploadChange"
              :auto-upload="false"
              :show-file-list="true"
            >
              <el-button slot="trigger" size="small" type="primary"
                >選取</el-button
              >
              <el-button
                style="margin-left: 10px"
                size="small"
                type="success"
                @click="submitUpload"
                >上傳</el-button
              >
            </el-upload>

判斷上傳的檔案是否符合預期:

onUploadChange(file) {
    //儲存上傳的檔案
      this.file[0] = file;
      const isIMAGE =
        file.raw.type === "video/mp4" || file.raw.type === "audio/mp4";
      const isLt1M = file.size / 1024 / 1024 / 1024 < 1;//大小要小於10MB

      if (!isIMAGE) {
        this.$message.error("上傳檔案只能是圖片格式!");
        return false;
      }
      if (!isLt1M) {
        this.$message.error("上傳檔案大小不能超過 10MB!");
        return false;
      }
}

上傳檔案:

submitUpload(event) {
      if (this.file.length == 0) {
        this.$message({
          type: "error",
          message: "未選取檔案",
        });
        return;
      }

      //event.preventDefault();
      let formData = new FormData();
      //資料
      formData.append("file", this.file[0].raw);
      formData.append("name", this.file[0].name);
      //請求頭
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      //請求路徑
      let url = "http://localhost:5501/videoToAudio";

      this.$axios.post(url, formData, config)
      .then((res) => {
            //上傳成功後要進行的操作
      })
      .catch((res) => {
        this.$message({
          type: "error",
          message: res
        })
      });
    }

file內容一般是如下圖格式:

 後端

controller:

@RequestMapping(value = "請求名",method = RequestMethod.POST)
    public void videoToAudio(@RequestParam("file") MultipartFile file,@RequestParam("name") String name){
        if (file != null){
            System.out.println("接收成功");
            System.out.println("檔名:"+name);
        }else{
            System.out.println("接收失敗");
        }

    }