久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Vue + Node.js + MongoDB圖片上傳組件實(shí)現(xiàn)圖片預(yù)覽和刪除功能詳解

瀏覽:49日期:2023-01-23 15:54:04

本文實(shí)例講述了Vue + Node.js + MongoDB圖片上傳組件實(shí)現(xiàn)圖片預(yù)覽和刪除功能。分享給大家供大家參考,具體如下:

公司要寫一些為自身業(yè)務(wù)量身定制的的組件,要基于Vue,寫完后擴(kuò)展了一下功能,選擇寫圖片上傳是因?yàn)樽约褐耙恢睂@個(gè)功能比較迷糊,所以這次好好了解了一下。演示在網(wǎng)址打開后的show.gif中。

使用技術(shù):Vue.js | node.js | express | MongoDB。

github網(wǎng)址:https://github.com/neroneroffy/private-project/tree/master/vue_uploader

Vue + Node.js + MongoDB圖片上傳組件實(shí)現(xiàn)圖片預(yù)覽和刪除功能詳解

功能 單圖多圖上傳 圖片上傳預(yù)覽 上傳進(jìn)度條 分組上傳,分組查詢 新建分組,刪除分組 刪除圖片 選擇圖片目錄結(jié)構(gòu)

Vue + Node.js + MongoDB圖片上傳組件實(shí)現(xiàn)圖片預(yù)覽和刪除功能詳解

前端利用Vue搭建,Entry.vue中引入子組件Upload.vue。在Upload.vue中,使用input標(biāo)簽,上傳圖片,form表單提交數(shù)據(jù),但是from讓人很頭疼,提交后刷新頁面,所以給它綁定了一個(gè)隱藏的iframe標(biāo)簽來實(shí)現(xiàn)無刷新提交表單。

Dom中:

<form enctype='multipart/form-data' ref='formSubmit' > <label class='upload-content-right-top-btn'>上傳圖片</label> <input type='file' @change='uploadImage($event)' multiple='multiple' accept='image/gif, image/jpeg, image/png'></form><iframe name='rfFrame' src='about:blank' style='display:none;'></iframe>

調(diào)用上傳函數(shù)提交完數(shù)據(jù)后:

upload();document.forms[0].target='rfFrame';

圖片預(yù)覽

利用html5的fileReader對象

let count = 0;//上傳函數(shù)外定義變量,記錄文件的數(shù)量,即遞歸的次數(shù)/*-----------------------此段代碼在上傳函數(shù)中-------------------------------*/ let fileReader = new FileReader(); //解析圖片路徑,實(shí)現(xiàn)預(yù)覽 fileReader.readAsDataURL(file.files[count]); fileReader.onload=()=>{ previewData = { url:fileReader.result,//圖片預(yù)覽的img標(biāo)簽的src name:file.files[count].name, size:file.files[count].size, }; //這段代碼在上傳函數(shù)中,所以在外面定義了一個(gè)_this = this,fileList為vue的data中定義的狀態(tài) _this.fileList.push(previewData); };

進(jìn)度條實(shí)現(xiàn)

在axios的配置中定義onUploadProgress函數(shù),接收參數(shù):progressEvent,利用它的兩個(gè)屬性:progressEvent.total和progressEvent.loaded(上傳的文件總字節(jié)數(shù)和已上傳的字節(jié)數(shù))node寫接口,實(shí)現(xiàn)圖片的接收、查詢、刪除。實(shí)現(xiàn)分組的新增、查詢、刪除。利用Formidable模塊接收并處理前端傳過來的表單數(shù)據(jù)。利用fs模塊實(shí)現(xiàn)刪除文件功能。

let progress = 0;let config = { headers: {’Content-Type’: ’multipart/form-data’}, onUploadProgress (progressEvent){ if(progressEvent.lengthComputable){ progress = progressEvent.total/progressEvent.loaded; _this.$refs.progress[_this.$refs.progress.length-1].style.width = Number(progress).toFixed(2)*100+'%'; } }};

向formData中插入文件

formData = new FormData();if(file.files[count]){formData.append(’file’,file.files[count],file.files[count].name);

對于上傳方式,我這里統(tǒng)一采用依次上傳,無論是單圖多圖,單圖上傳一次就好,多圖則遞歸調(diào)用上傳函數(shù),直到遞歸次數(shù)等于圖片數(shù)量,停止遞歸。

上傳函數(shù)

let file=$event.target,formData = new FormData();//遞歸調(diào)用自身,實(shí)現(xiàn)多文件依次上傳let _this = this;let count = 0;let previewData = {};uploadImage($event){ let file=$event.target, formData = new FormData(); //遞歸調(diào)用自身,實(shí)現(xiàn)多文件依次上傳 let _this = this; let count = 0; let previewData = {}; function upload(){ //開始上傳時(shí),滾到底部 _this.$refs.picWrapper.scrollTop = _this.$refs.picWrapper.scrollHeight; //定義axios配置信息 let progress = 0; let config = { headers: {’Content-Type’: ’multipart/form-data’}, onUploadProgress (progressEvent){ console.log(`進(jìn)度條的數(shù)量${_this.$refs.progress.length -1}`); if(progressEvent.lengthComputable){ progress = progressEvent.total/progressEvent.loaded; //進(jìn)度條 _this.$refs.progress[_this.$refs.progress.length-1].style.width = Number(progress).toFixed(2)*100+'%'; } } }; //向formData中插入文件 if(file.files[count]){ formData.append(’file’,file.files[count],file.files[count].name); let fileReader = new FileReader(); //解析圖片路徑,實(shí)現(xiàn)預(yù)覽 fileReader.readAsDataURL(file.files[count]); fileReader.onload=()=>{ previewData = { url:fileReader.result, name:file.files[count].name, size:file.files[count].size, }; _this.fileList.push(previewData); _this.progressShow = true }; fileReader.onloadend=()=>{ //檢測圖片大小是否超出限制 if(formData.get(’file’).size>_this.maxSize){ formData.delete(’file’); //當(dāng)圖片全部上傳完畢,停止遞歸 count++; if(count > file.files.length-1){ return } upload() }else{ //發(fā)送數(shù)據(jù) axios.post(`/upload?mark=${_this.group}`,formData,config).then((response)=>{formData.delete(’file’);let res = response.data;console.log(res);if(res.result){ //如果是新建上傳 if(_this.group === ’new’){ _this.fileList.push(res.data); _this.fileList.forEach((item,index)=>{ if(!item.newName){ _this.fileList.splice(index,1) } }) }else{ //如果是選擇其他組上傳,直接把返回?cái)?shù)據(jù)賦值到文件數(shù)組 _this.fileList = res.data; } _this.newUpload = false}else{ alert(’上傳失敗’); return;}_this.noPic = false;count++;if(count > file.files.length-1){ return}upload() }).catch((err)=>{alert(’上傳失敗123’); }); } }; } } //第一次調(diào)用 upload(); document.forms[0].target='rfFrame';}node.js寫后端

//引入表單處理模塊let Formidable = require('formidable');

一系列定義....

form.encoding = ’utf-8’;form.uploadDir = ’/project/vue/vue_uploader/my-server/public/images’;//定義文件存放地址form.keepExtensions = true;form.multiples = false;//以單文件依次上傳的方式,實(shí)現(xiàn)多文件上傳form.maxFieldsSize = 1*1024;//解析圖片,重命名圖片名稱,返回給前端。let fileData = '';let fileDir = 'images';//定義文件的存放路徑let route = ’upload_’;//定義路由let serverIp = ’http://localhost:3002/’;//定義服務(wù)器IP

對文件數(shù)據(jù)進(jìn)行處理,存入本地并存入數(shù)據(jù)庫(由于涉及到分組上傳。。。所以比較復(fù)雜)

解析文件函數(shù):

function handleFile (file){ let filename = file.name; let nameArray = filename.split(’.’); let type = nameArray[nameArray.length-1]; let name = ’’; for (let i = 0;i<nameArray.length - 1;i++){ name = name + nameArray[i]; } let date = new Date(); let time = ’_’ + date.getFullYear() + '_' + date.getMonth() + '_' + date.getDay() + '_' + date.getHours() + '_' + date.getMinutes() +'_'+ date.getSeconds()+'_'+date.getMilliseconds(); let picName = name + time + ’.’ + type; let newPath = form.uploadDir + '/' + picName; let oldPath = form.uploadDir + '/'+ file.path.substring(file.path.indexOf(route)); fs.renameSync(oldPath, newPath); //重命名 fileData = { id:`${new Date().getTime()}`, url:serverIp + newPath.substring(newPath.indexOf(fileDir)), name:file.name, size:file.size, isSelected:false, newName:picName, }; UploadData.findOne({group:group},(err,doc)=>{ if(err){ res.json({result:false,msg:err.message }) }else{ if(doc){doc.picList.push(fileData);doc.save((err,saveResult)=>{ if(err){ return res.json({ result:false, }); }else{ let length= doc.picList.length; console.log(doc.picList.length) if(groupMark === ’all’){ UploadData.find({},(err,queryResult)=>{if(err){ res.json({ result:false, mgs:’發(fā)生錯(cuò)誤了’ })}else{ let allPic = []; queryResult.forEach((item)=>{ if(item.group !==’default’){ allPic = allPic.concat(item.picList) } }); res.json({ result:true, data:allPic.concat(queryResult[1].picList) })} }) }else if(groupMark === ’new’){ UploadData.findOne({group:’default’},(err,queryResult)=>{if(err){ return res.json({ result:false, msg:err.message });}else{ return res.json({ result:true, data:queryResult.picList[queryResult.picList.length-1] })} }); }else{ UploadData.findOne({group:group},(err,queryResult)=>{if(err){ return res.json({ result:false, msg:err.message });}else{ return res.json({ result:true, data:queryResult.picList })} }); } }}) } } })}

最后,調(diào)用解析文件函數(shù)

form.parse(req,(err,fields,files)=>{ //傳多個(gè)文件 if(files.file instanceof Array){ return }else{ //傳單個(gè)文件 handleFile(files.file) }});

數(shù)據(jù)庫結(jié)構(gòu):

Vue + Node.js + MongoDB圖片上傳組件實(shí)現(xiàn)圖片預(yù)覽和刪除功能詳解

剩下的還有文件刪除,新增分組,刪除分組,分組查詢的功能,由于篇幅有限,這些功能可以去看源碼

第一次用node和mongoDB寫后臺業(yè)務(wù),還有很多地方需要完善,代碼會(huì)繼續(xù)更新~

希望本文所述對大家vue.js程序設(shè)計(jì)有所幫助。

標(biāo)簽: Vue
相關(guān)文章:
主站蜘蛛池模板: 宾川县| 噶尔县| 栖霞市| 平果县| 万安县| 本溪| 广宗县| 交城县| 海丰县| 乐至县| 舒兰市| 怀宁县| 鄂伦春自治旗| 阿图什市| 宁安市| 怀宁县| 阿勒泰市| 庆安县| 改则县| 保定市| 无锡市| 金沙县| 花莲市| 万荣县| 汕尾市| 班玛县| 廊坊市| 和田市| 徐闻县| 甘泉县| 阿城市| 黄大仙区| 宁津县| 依安县| 咸阳市| 邹平县| 九龙城区| 香格里拉县| 平凉市| 长子县| 台中县|