This time I will bring you a lightweight file upload component encapsulated in vue. What are the precautions for encapsulating a lightweight file upload component in vue? The following is a practical case, let's take a look.
1. Some problems encountered before
There are many requirements for uploading files in the project, which is implemented using the existing UI framework During the process, there will always be some inexplicable bugs for some unknown reason. For example, when using a certain upload component, it is clearly marked (:multiple="false"), but in fact it is still possible to select multiple files, and multiple files are still sent when uploading; for example, as long as (:file-list="fileList" is added) ") attribute, when I hope to manually control the upload list, the upload event this.refs.[upload (component ref)].submit() will not work and cannot be transmitted. In short, I am too lazy to see how to implement it. I am using the function, and the interface itself still needs to be rewritten. If I insist on using it, it will add a lot of unnecessary logic and style code to the project...
Used before The view frameworks used by Vue for projects include element-ui, zp-ui as a supplement within the team, and iview. The framework is easy to use, but you often can’t use it for your own projects. Especially the interface created by our design girl is very different from the existing framework. Changing the source code is inefficient and can easily lead to unknown bugs, so I take the time to do it myself. Encapsulates this upload component.
2. Code and introduction
Parent component
The parent component handles business-related logic, I specially added it The index parameter allows the interface to directly manipulate the value when displaying the upload result. It is not required for all methods and can be used according to needs.
Subcomponent
Upload the file, the html part is just a pair of tags, I don’t like the complexity
This defines the attributes that need to be passed from the parent component to the child component Value, please note that the method is also passed as an attribute here, which is acceptable.
The components I wrote are not as complete and comprehensive as those released by popular frameworks. In addition, in view of the problem mentioned at the beginning that the bound file-list cannot be uploaded (more likely because my posture is wrong), I I also want to try my best to solve this problem I encountered, so I hope to have absolute control over the file list. In addition to action, file-list is also used as an attribute that must be passed by the parent component. (The attribute name of the parent component is connected with "-", corresponding to the camel case naming in the child component prop)
3. Main upload function
methods: { addFile, remove, submit, checkIfCanUpload }
addFile({target: {files}}){//input标签触发onchange事件时,将文件加入待上传列表 for(let i = 0, l = files.length; i < l; i++){ files[i].url = URL.createObjectURL(files[i]);//创建blob地址,不然图片怎么展示? files[i].status = 'ready';//开始想给文件一个字段表示上传进行的步骤的,后面好像也没去用...... } let fileList = [...this.fileList]; if(this.multiple){//多选时,文件全部压如列表末尾 fileList = [...fileList, ...files]; let l = fileList.length; let limit = this.limit; if(limit && typeof limit === "number" && Math.ceil(limit) > 0 && l > limit){//有数目限制时,取后面limit个文件 limit = Math.ceil(limit); // limit = limit > 10 ? 10 : limit; fileList = fileList.slice(l - limit); } }else{//单选时,只取最后一个文件。注意这里没写成fileList = files;是因为files本身就有多个元素(比如选择文件时一下子框了一堆)时,也只要一个 fileList = [files[0]]; } this.onChange(fileList);//调用父组件方法,将列表缓存到上一级data中的fileList属性 },
remove(index){ let fileList = [...this.fileList]; if(fileList.length){ fileList.splice(index, 1); this.onChange(fileList); } },
submit(){ if(this.checkIfCanUpload()){ if(this.onProgress && typeof XMLHttpRequest !== 'undefined') this.xhrSubmit(); else this.fetchSubmit(); } },
fetchSubmit(){ let keys = Object.keys(this.data), values = Object.values(this.data), action = this.action; const promises = this.fileList.map(each => { each.status = "uploading"; let data = new FormData(); data.append(this.name || 'file', each); keys.forEach((one, index) => data.append(one, values[index])); return fetch(action, { method: 'POST', headers: { "Content-Type" : "application/x-www-form-urlencoded" }, body: data }).then(res => res.text()).then(res => JSON.parse(res));//这里res.text()是根据返回值类型使用的,应该视情况而定 }); Promise.all(promises).then(resArray => {//多线程同时开始,如果并发数有限制,可以使用同步的方式一个一个传,这里不再赘述。 let success = 0, failed = 0; resArray.forEach((res, index) => { if(res.code == 1){ success++; //统计上传成功的个数,由索引可以知道哪些成功了 this.onSuccess(index, res); }else if(res.code == 520){ //约定失败的返回值是520 failed++; //统计上传失败的个数,由索引可以知道哪些失败了 this.onFailed(index, res); } }); return { success, failed }; //上传结束,将结果传递到下文 }).then(this.onFinished); //把上传总结果返回 },
xhrSubmit(){ const _this = this; let options = this.fileList.map((rawFile, index) => ({ file: rawFile, data: _this.data, filename: _this.name || "file", action: _this.action, onProgress(e){ _this.onProgress(index, e);//闭包,将index存住 }, onSuccess(res){ _this.onSuccess(index, res); }, onError(err){ _this.onFailed(index, err); } })); let l = this.fileList.length; let send = async options => { for(let i = 0; i < l; i++){ await _this.sendRequest(options[i]);//这里用了个异步方法,按次序执行this.sendRequest方法,参数为文件列表包装的每个对象,this.sendRequest下面紧接着介绍 } }; send(options); },
sendRequest(option){ const _this = this; upload(option); function getError(action, option, xhr) { var msg = void 0; if (xhr.response) { msg = xhr.status + ' ' + (xhr.response.error || xhr.response); } else if (xhr.responseText) { msg = xhr.status + ' ' + xhr.responseText; } else { msg = 'fail to post ' + action + ' ' + xhr.status; } var err = new Error(msg); err.status = xhr.status; err.method = 'post'; err.url = action; return err; } function getBody(xhr) { var text = xhr.responseText || xhr.response; if (!text) { return text; } try { return JSON.parse(text); } catch (e) { return text; } } function upload(option) { if (typeof XMLHttpRequest === 'undefined') { return; } var xhr = new XMLHttpRequest(); var action = option.action; if (xhr.upload) { xhr.upload.onprogress = function progress(e) { if (e.total > 0) { e.percent = e.loaded / e.total * 100; } option.onProgress(e); }; } var formData = new FormData(); if (option.data) { Object.keys(option.data).map(function (key) { formData.append(key, option.data[key]); }); } formData.append(option.filename, option.file); xhr.onerror = function error(e) { option.onError(e); }; xhr.onload = function onload() { if (xhr.status < 200 || xhr.status >= 300) { return option.onError(getError(action, option, xhr)); } option.onSuccess(getBody(xhr)); }; xhr.open('post', action, true); if (option.withCredentials && 'withCredentials' in xhr) { xhr.withCredentials = true; } var headers = option.headers || {}; for (var item in headers) { if (headers.hasOwnProperty(item) && headers[item] !== null) { xhr.setRequestHeader(item, headers[item]); } } xhr.send(formData); return xhr; } }
checkIfCanUpload(){ return this.fileList.length ? (this.onBefore && this.onBefore() || !this.onBefore) : false; },
p5.js uses the draw() function to make a golden spiral
How to use it in actual projects jquery filter()
The above is the detailed content of vue encapsulates lightweight file upload component. For more information, please follow other related articles on the PHP Chinese website!