<a-upload
      v-model:file-list="fileList"
      :show-upload-list="false"
      :multiple="true"
      :before-upload="beforeUpload"
      :customRequest="selfUpload"
      accept=".png,.jpg"
    >
      <a-button> 上传图片 </a-button>
    </a-upload>

第一种formDate

/**
   * 发送post请求(特殊)
   * @param {string} url 地址
   * @param {object} data 请求数据
   * @param {Function} done 成功回调
   * @param {Function} fail 失败回调(可选)
   */
  postAdmin(Url, params, data, done, fail) {
    const url = params ? `${Url}?${convertParams(params)}` : Url;
    return axios
      .post(url, data)
      .then((data) => {
        return data.data
      }
      )
      .catch((error) => {
        console.log(error);
        console.log(fail);
      });
  },
 // 上传文件
    beforeUpload(file) {
      this.fileList = [...this.fileList, file];
      // return false;
    },
    selfUpload() {
      this.handleUpload();
    },
    async handleUpload() {
         if(this.fileList.length == 0) {
        this.$message.error('请上传文件')
        return false
      }
      const formData = new FormData();
      this.fileList.forEach((file) => {
        formData.append("files", file);
      });
      console.log(formData);
      const res = await this.$api.batchUploadDrillImage(
        { drillId: parseInt(sessionStorage.getItem("drillid")) },
        formData
      );
      this.$message.success(res);
      console.log(res);
    },

第二种

selfUpload({file}){
      const base64 = new Promise(resolve => {
        const fileReader = new FileReader()
        fileReader.readAsDataURL(file)
        fileReader.onload = () => {
          resolve(fileReader.result)
          this.imageUrl = fileReader.result
          this.UploadSmallPic(fileReader.result)
        }
      })
    },// 上传图片
    async UploadSmallPic(str){
      str = str.replace(/^data:image\/\w+;base64,/, "")
      const res = await this.$api.batchUploadDrillImage({
         drillId:parseInt(sessionStorage.getItem("drillid")),
          pic: str
      })
      console.log(res);
    },
    // 图片上传前限制
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJpgOrPng) {
        this.$message.error('您只能选择JPG的图片格式上传');
      }
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB');
      }
      return isJpgOrPng&&isLt2M;
    },
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐