CustomRequest allows you to customize your own upload method
Demand scenarios
In the background management system, the UI framework is Ant Design of Vue and the Upload component is used to Upload pictures.
Requirement description: Upload the image and convert it to Base64
Implementation method
In the API method, there is a custom upload behavior method, by overwriting the default upload behavior, you can customize your own upload implementation
CustomRequest Custom upload method
<a-form-item
:labelCol="labelCol"
:wrapperCol="wrapperCol"
label="Photos">
<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="Avatar" style="height:104px; max-width:300px"/>
<div v-else>
<a-icon :type="uploadLoading ? 'loading' : 'plus'" />
<div class="ant-upload-text">upload</div>
</div>
</a-upload>
</a-form-item>
Copy the code
The uploaded image is converted to Base64
// Handle uploaded files
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;}}); }Copy the code