前端向后端傳文件


前端使用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("接收失敗");
        }

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM