The introduction
Uploading files is a common requirement in our daily development. At this time, everyone who uses Vue will think of the el-upload component, but our requirements often need to upload multiple files, pass parameters, etc. At this point, we need to use the HTTP-Request in it to do a custom upload.
Upload the file is relatively simple, you can directly watch the complete code part, a look that understand. The upload request is shown below:
Traditional Form submission
There are many ways to upload files. The upload of the el-upload component essentially uses the form submission, and the upload is usually a binary file to the back end.
<input type="file" id="upload"> console.log($("#upload").files); => get an array of binary files.Copy the code
However, such a method cannot meet our development requirements, he can only get the uploaded files, and if the user adds or deletes files or uploads files that do not meet the requirements, we still need to make further judgment.
So, we can use the el-Upload component directly, customize the upload, and use its wrapped hook functions.
Custom upload of el-upload
Using the HTTP-Request property in the component, the assignment is our upload function. Then cooperate with on-change and on-remove in the component to get the File we need.
// let formData = new formData (); this.upload_List.forEach((item, index) => { formData.append("file", FileXX); // Add file}); Because AppEnd adds a new value to an existing key of the instance object, it adds the key if it doesn't already exist. Push (XXX) can be interpreted as => file: [].push(XXX). Therefore, multiple files can be uploaded at a time or a single file can be uploaded in this way.Copy the code
FormData.append()
1. Avoid pit
During the development, I found that: (1) When deleting a file, the raw of the file was object, not file. (2) When a user uplows a file for the second time, the parameter filelist in on-change contains an object raw file, not a file. So, in on-change, on-remove, we can’t just take a filelist and assign it to it. Instead, we add and remove a member of a new array.
2. The complete code is as follows (including some judgments)
<el-upload id="upload" ref="upload" drag multiple :limit="100" :file-list="fileList" action="#" :http-request="Execute_File" :auto-upload="false" :on-change="upload_change" :on-remove="upload_remove" :on-exceed="upload_exceed" >< I class="el-icon-upload"></ I >< div class="el-upload__text"> <em> </div> </el-upload> data(){return {fileList: [], // [], // upload file, notifyPromise: promise.resolve () // Resolve Notification component height collapse problem}; } methods:{upload_change: function(file, fileList) {1M if (file.size > 1048576) {filelist.pop (); Let msg_size = 'you uploaded ${file.name}, the file is larger than 1M, please upload again. `; this.notify_self(msg_size, "size"); return false; } let repeat_judge = this.filelist. find(item => {return item.name == file.name; }); if (repeat_judge) { fileList.pop(); Let msg_repeat = 'you uploaded ${file.name}, this file has the same name file, please re-upload. `; this.notify_self(msg_repeat, "repeat"); return false; } this.fileList = JSON.parse(JSON.stringify(fileList)); this.upload_List.push(file); }, upload_remove(file, fileList) { this.fileList = JSON.parse(JSON.stringify(fileList)); // Do not directly assign the value because in the printed data, if multiple files are deleted to only one, the raw of the file is object. ForEach ((item, index) => {if (item.name == file.name) {this.upload_list.splice (index, 1); }}); }, upload_exceed(files, fileList) {this.$alert(" You can upload a maximum of 100 files! , {confirmButtonText: "confirmButtonText ", type: "warning"}); }, notify_self(msg, type) { this.notifyPromise = this.notifyPromise.then(this.$nextTick).then(() => { this.$notify({ title: `${type == "size" ? } ', message: MSG, iconClass: '${type == "size"? "el-icon-s-opportunity" : "el-icon-message-solid" }`, customClass: `${type == "size" ? "notify_size" : "notify_repeat"}`, duration: 6000 }); }); }, Execute_File() {// transfer file let formData = new formData (); this.upload_List.forEach((item, index) => { formData.append("file", item.raw); }); $.axios({ url:"XXX", method:"post", data: FormData, params: {test2 test1: "1" : "2"} / /} refs). Then (res = > {}). The catch (res = > {})},}Copy the code
3. Notification component. Component height collapse problem
As an aside, when judging the uploading of files, if they are not in accordance with the rules, we will notify them through element’s Notification component, but this component has a problem of high collapse.
data(){
notifyPromise: Promise.resolve()
},
this.notifyPromise = this.notifyPromise.then(this.$nextTick).then(() => {
this.$notify({
title: "111111",
message: "22222",
});
});
Copy the code
This solution is baidu come, hey hey, original blog link: As FAR as I am aware, the overlapping problem of element-UI Notification will be changed into a synchronous operation process through Promise, and the updated DOM state will be obtained through this.$nextTick. After dom update, the Notification component will be executed.
Emmm To tell you the truth, I don’t understand his way of writing grammatical sugar here. In my understanding, the way of writing above is actually the process of writing below, but it didn’t work after I rewrote it like this. Have eldest brother to understand words, troublesome comment area leave a message, guide.
this.notifyPromise = new Promise((resolve, reject) => {
resolve();
})
.then(() => {
return new Promise((resolve, reject) => {
this.$nextTick(() => {
resolve();
});
});
})
.then(() => {
this.$notify({
title: "111111",
message: "22222"
});
});
Copy the code
Stern said
Good people live a safe life, give my brother a thumbs up ~