Ant Design of Vue 的Upload 组件customRequest自定义上传方法

3,332 阅读1分钟

customRequest 可以自定义自己的上传方法

需求场景

后台管理系统,UI框架是Ant Design of Vue上传图片用的是Upload组件。

需求描述:上传图片,转为base64

实现方法

API方法中,有一个自定义上传行为的方法,通过覆盖默认的上传行为,可以自定义自己的上传实现

customRequest自定义上传方法

<a-form-item
  :labelCol="labelCol"
  :wrapperCol="wrapperCol"
  label="照片">
  <a-upload
    v-decorator="['zp', validatorRules.zp]"
    listType="picture-card"
    class="avatar-uploader"
    :showUploadList="false"
    :beforeUpload="beforeUpload"
    :customRequest="selfUpload"
  >
    <img v-if="picUrl" :src="getAvatarView()" alt="头像" style="height:104px;max-width:300px"/>
    <div v-else>
      <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">上传</div>
    </div>
  </a-upload>
​
</a-form-item>

上传的图片转为base64

//对上传的文件处理
selfUpload ({ action, file, onSuccess, onError, onProgress }) {
     console.log(file, 'action, file');
     const base64 = new Promise(resolve => {
         const fileReader = new FileReader();
         fileReader.readAsDataURL(file);
         fileReader.onload = () => {
              resolve(fileReader.result);
              // this.formImg = fileReader.result;
          }
      });
}
​