This is the first day of my participation in Gwen Challenge
preface
Front-end file upload is a common requirement. The Element – UI upload component provides great convenience to front-end developers and simplifies their work. However, because components need to adapt to various conditions, it is difficult to complete some specific requirements only by relying on the components themselves.
Like I did in my last project. There are many forms maintenance pages that also include file uploads, back-end interfaces that require the file to be passed along with the form data, and sometimes require the file to be uploaded after the form data has been submitted. Then we need to modify the Upload component of the Element-UI to upload files through our custom request.
Note here the considerations of uploading files via custom requests using the Element-UI upload component.
code
Component itself
The upload component itself serves the purpose of retrieving the file object. Type =file using the input tag can do the same.
upload.vue
<el-upload ref="uploadMutiple" :auto-upload="false" action="Fake Action" :on-success="allHandleSuccess" :on-change="handleChange" :file-list="fileList" :http-request="allUpload" :before-upload="before_upload" multiple </el-button type="primary" size="small" @click="submitUpload"> </el-button>Copy the code
First turn off automatic upload and assign a string to any action. (Action is required)
:auto-upload="false"
action="Fake Action"
Copy the code
Get the list of files using the :on-change hook function:
handleChange(file, fileList) {
this.fileList = fileList;
},
Copy the code
Normally, we trigger an upload in the click event of a submitUpload () :
submitUpload() {
this.$refs.uploadMutiple.submit();
}
Copy the code
Encapsulating file objects
The component then fires: number of HTTP-Request hook lines. Note that if you have several files in your fileList, you will execute the http-Request hook function several times. This means that if you write the upload request in the http-Request hook function, you will end up repeating unnecessary requests. Simply write the POST request in submitUpload(). Just wrap the file as a formData object and pass it to the background as a parameter.
let formData = new FormData();
this.fileList.forEach(item= > {
formData.append("files", item.raw);
});
this.axios.post(api, formData);
Copy the code
The following is the background interface:
public JSONResponse archiveBatchImport(@RequestParam("files") MultipartFile[] files){}
Copy the code
conclusion
Not long after contact with front-end development, we still took many detours in realizing such requirements, during which we also tried to package and upload components by ourselves, and the result was that the components looked like a car with three rotten tires. Once you’re familiar with component apis, you should also think about what goes on behind the scenes.