亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

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

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

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

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

公司要寫一些為自身業(yè)務(wù)量身定制的的組件,要基于Vue,寫完后擴展了一下功能,選擇寫圖片上傳是因為自己之前一直對這個功能比較迷糊,所以這次好好了解了一下。演示在網(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圖片上傳組件實現(xiàn)圖片預(yù)覽和刪除功能詳解

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

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

前端利用Vue搭建,Entry.vue中引入子組件Upload.vue。在Upload.vue中,使用input標(biāo)簽,上傳圖片,form表單提交數(shù)據(jù),但是from讓人很頭疼,提交后刷新頁面,所以給它綁定了一個隱藏的iframe標(biāo)簽來實現(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(); //解析圖片路徑,實現(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ù)中,所以在外面定義了一個_this = this,fileList為vue的data中定義的狀態(tài) _this.fileList.push(previewData); };

進度條實現(xiàn)

在axios的配置中定義onUploadProgress函數(shù),接收參數(shù):progressEvent,利用它的兩個屬性:progressEvent.total和progressEvent.loaded(上傳的文件總字節(jié)數(shù)和已上傳的字節(jié)數(shù))node寫接口,實現(xiàn)圖片的接收、查詢、刪除。實現(xiàn)分組的新增、查詢、刪除。利用Formidable模塊接收并處理前端傳過來的表單數(shù)據(jù)。利用fs模塊實現(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)用自身,實現(xiàn)多文件依次上傳let _this = this;let count = 0;let previewData = {};uploadImage($event){ let file=$event.target, formData = new FormData(); //遞歸調(diào)用自身,實現(xiàn)多文件依次上傳 let _this = this; let count = 0; let previewData = {}; function upload(){ //開始上傳時,滾到底部 _this.$refs.picWrapper.scrollTop = _this.$refs.picWrapper.scrollHeight; //定義axios配置信息 let progress = 0; let config = { headers: {’Content-Type’: ’multipart/form-data’}, onUploadProgress (progressEvent){ console.log(`進度條的數(shù)量${_this.$refs.progress.length -1}`); if(progressEvent.lengthComputable){ progress = progressEvent.total/progressEvent.loaded; //進度條 _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(); //解析圖片路徑,實現(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{ //如果是選擇其他組上傳,直接把返回數(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;//以單文件依次上傳的方式,實現(xiàn)多文件上傳form.maxFieldsSize = 1*1024;//解析圖片,重命名圖片名稱,返回給前端。let fileData = '';let fileDir = 'images';//定義文件的存放路徑let route = ’upload_’;//定義路由let serverIp = ’http://localhost:3002/’;//定義服務(wù)器IP

對文件數(shù)據(jù)進行處理,存入本地并存入數(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ā)生錯誤了’ })}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)=>{ //傳多個文件 if(files.file instanceof Array){ return }else{ //傳單個文件 handleFile(files.file) }});

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

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

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

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

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

標(biāo)簽: Vue
相關(guān)文章:
主站蜘蛛池模板: 一本伊人 | 色播亚洲视频在线观看 | 800玖玖爱在线观看香蕉 | 欧美日韩亚洲国产千人斩 | 国产又色又粗又黄又爽免费 | 免费视频黄 | 精品国产自在久久 | 99国产精品一区二区 | 最新69成人精品毛片 | 国产在线综合网 | 亚洲精品视频久久久 | 欧美美女一区二区三区 | 国产成人啪午夜精品网站 | 福利视频在线看 | 污污网站免费 | 在线看三级aaa | 国产性感美女视频 | 欧美黄色一级在线 | 分享一个无毒不卡免费国产 | 亚洲欧美日韩专区一 | 久热精品男人的天堂在线视频 | 欧美一区二区三区综合色视频 | 欧美一级毛片欧美大尺度一级毛片 | 欧美日韩亚毛片免费观看 | 不卡一区在线观看 | 亚洲国产欧美日韩一区二区三区 | 久久一区二区三区99 | 尤物视频网站在线观看 | 黄色免费a级片 | 欧美一级毛片片免费 | 日本不卡高清免费v日本 | 999久久久精品视频在线观看 | 国产福利视频 | 国产a级特黄的片子视频免费 | 黄色短视频在线播放 | 国产精品综合久成人 | 日韩精品视频在线免费观看 | 瑟瑟网站免费 | 狠狠色综合久久丁香婷婷 | 激情五月色综合色婷婷 | 婷婷激情狠狠综合五月 |