新聞中心
本文實(shí)例講述了vue實(shí)現(xiàn)的上傳圖片到數(shù)據(jù)庫并顯示到頁面功能。分享給大家供大家參考,具體如下:

創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站制作、成都網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的河口網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
1、點(diǎn)擊上傳圖片,彈出選擇圖片選項(xiàng)框。
頁面代碼:
上傳圖片![]()
由于我們要設(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對象。
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對象添加數(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請求
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("請求出錯(cuò)");
})
})
} else {
alert("文件格式不支持上傳");
}
}
希望本文所述對大家vue.js程序設(shè)計(jì)有所幫助。
網(wǎng)站標(biāo)題:vue實(shí)現(xiàn)的上傳圖片到數(shù)據(jù)庫并顯示到頁面功能示例
文章分享:http://www.dlmjj.cn/article/gpphed.html


咨詢
建站咨詢
