本文實(shí)例講述了vue實(shí)現(xiàn)的上傳圖片到數(shù)據(jù)庫并顯示到頁面功能。分享給大家供大家參考,具體如下:
1、點(diǎn)擊上傳圖片,彈出選擇圖片選項(xiàng)框。
頁面代碼:
<div class="form-signin-heading" id="btnUpload" @change="upload">上傳圖片</div><input type="file" name="avatar" id="avatar" multiple="multiple" @change="upload"><img :src="'http://localhost:8888'+item.photos_url" alt=""/>
由于我們要設(shè)置上傳圖片的樣式,所以把input隱藏,并要做如下操作把input的點(diǎn)擊事件給div框:
mounted: function () { var upload = document.getElementById("btnUpload"); var avatar = document.getElementById("avatar"); upload.onclick =function(){ avatar.click(); //注意IE的兼容性 };}2、在api接口的controller層加入兩個(gè)文件,命名自己定,如:
upFile.js
let multer=require('multer');let storage = multer.diskStorage({ //設(shè)置上傳后文件路徑,uploads文件夾會(huì)自動(dòng)創(chuàng)建。 destination: function (req, file, cb) { cb(null, './public/uploads') }, //給上傳文件重命名,獲取添加后綴名 filename: function (req, file, cb) { let fileFormat = (file.originalname).split("."); cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]); }});//添加配置文件到multer對(duì)象。let upload = multer({ storage: storage});module.exports = upload;upFileController.js
var muilter = require('./upFile.js');//multer有single()中的名稱必須是表單上傳字段的name名稱。var upload=muilter.single('file');function dataInput(req, res) { upload(req, res, function (err) { //添加錯(cuò)誤處理 if (err) { return console.log(err); } //文件信息在req.file或者req.files中顯示。 let photoPath = req.file.path; photoPath = photoPath.replace(/public/,"");//將文件路徑中的public/去掉,否則會(huì)和靜態(tài)資源配置沖突 //將photoPath存入數(shù)據(jù)庫即可 console.log(photoPath); res.send(photoPath); });}module.exports = { dataInput};3、在頁面中將圖片的地址存到數(shù)據(jù)庫
upload: function (e) { var that = this; let formData = new window.FormData(); let file = e.target.files[0]; formData.append('file',file);//通過append向form對(duì)象添加數(shù)據(jù) //利用split切割,拿到上傳文件的格式 var src = file.name, formart = src.split(".")[1]; //使用if判斷上傳文件格式是否符合 if (formart == "jpg" || formart == "png" || formart == "docx" || formart == "txt" || formart == "ppt" || formart == "xlsx" || formart == "zip" || formart == "rar" || formart == "doc") { //只有滿足以上格式時(shí),才會(huì)觸發(fā)ajax請(qǐng)求 this.$axios.post(this.$api.personalCenter.upFile,formData).then(function (res) { that.upFileData = res.data; }).then(function (res) { var params = { photos_url: that.upFileData, photo_des: '' };// console.log(params.photos_url,'photos_url') that.$axios.post(that.$api.personalCenter.wallAdd,qs.stringify(params)).then(function (res) { console.log(res.data); that.$options.methods.imgList.bind(that)(); }).catch(function (err) { console.log(err); console.log("請(qǐng)求出錯(cuò)"); }) }) } else { alert("文件格式不支持上傳"); }}希望本文所述對(duì)大家vue.js程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注