您好,登錄后才能下訂單哦!
怎么在vue中使用node上傳圖片并預覽?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
Vue具體輕量級框架、簡單易學、雙向數(shù)據(jù)綁定、組件化、數(shù)據(jù)和結構的分離、虛擬DOM、運行速度快等優(yōu)勢,Vue中頁面使用的是局部刷新,不用每次跳轉頁面都要請求所有數(shù)據(jù)和dom,可以大大提升訪問速度和用戶體驗。
<template> <div> <myheader :title="'發(fā)布動態(tài)'"> <i class="iconfont icon-fanhui1 left" slot="left" @click="goback"></i> </myheader> <div class="upload"> <div v-if="userInfo._id"> <!--圖片上傳--> <div class="weui-gallery" id="gallery"> <span class="weui-gallery__img" id="galleryImg"></span> <div class="weui-gallery__opr"> <a href="javascript:" rel="external nofollow" class="weui-gallery__del"> <i class="weui-icon-delete weui-icon_gallery-delete"></i> </a> </div> </div> <div class="weui-cells weui-cells_form"> <div class="weui-cell"> <div class="weui-cell__bd"> <textarea class="weui-textarea" v-model="content" placeholder="你想說啥" rows="3"></textarea> </div> </div> <div class="weui-cell"> <div class="weui-cell__bd"> <div class="weui-uploader"> <div class="weui-uploader__bd"> <ul class="weui-uploader__files" id="uploaderFiles"> <li ref="files" class="weui-uploader__file" v-for="(image,index) in images" :key="index" :><span @click="deleteimg(index)" class="x">×</span></li> </ul> <div v-show="images.length < maxCount" class="weui-uploader__input-box"> <input @change="change" id="uploaderInput" class="weui-uploader__input " type="file" multiple accept="image/*"> </div> </div> </div> </div> </div> </div> <a class="weui-btn weui-btn_primary btn-put" @click.prevent.once="put">發(fā)送</a> </div> <unlogin v-else> </unlogin> </div> </div> </template>
重點部分在于
<ul class="weui-uploader__files" id="uploaderFiles"> <li ref="files" class="weui-uploader__file" v-for="(image,index) in images" :key="index" :><span @click="deleteimg(index)" class="x">×</span></li> </ul> <div v-show="!this.$refs.files||this.$refs.files.length < maxCount" class="weui-uploader__input-box"> <input @change="change" id="uploaderInput" class="weui-uploader__input" type="file" multiple accept="image/*"> </div>
通過@change="change"監(jiān)聽圖片的上傳,把圖片轉成base64后(后面會講怎么轉base64)將base64的地址加入到images數(shù)組,通過v-for="(image,index) in images"把要上傳的圖片在頁面中顯示出來,即達到了預覽的效果
js部分
data部分
data() { return { content: '',//分享動態(tài)的文字內容 maxSize: 10240000 / 2,//圖片的最大大小 maxCount: 8,//最大數(shù)量 filesArr: [],//保存要上傳圖片的數(shù)組 images: []//轉成base64后的圖片的數(shù)組 } }
delete方法
deleteimg(index) { this.filesArr.splice(index, 1); this.images.splice(index, 1); }
change方法
change(e) { let files = e.target.files; // 如果沒有選中文件,直接返回 if (files.length === 0) { return; } if (this.images.length + files.length > this.maxCount) { Toast('最多只能上傳' + this.maxCount + '張圖片!'); return; } let reader; let file; let images = this.images; for (let i = 0; i < files.length; i++) { file = files[i]; this.filesArr.push(file); reader = new FileReader(); if (file.size > self.maxSize) { Toast('圖片太大,不允許上傳!'); continue; } reader.onload = (e) => { let img = new Image(); img.onload = function () { let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); let w = img.width; let h = img.height; // 設置 canvas 的寬度和高度 canvas.width = w; canvas.height = h; ctx.drawImage(img, 0, 0, w, h); let base64 = canvas.toDataURL('image/png'); images.push(base64); }; img.src = e.target.result; }; reader.readAsDataURL(file); } }
put方法把filesArr中保存的圖片通過axios發(fā)送到后端,注意要設置headers信息
put() { Indicator.open('發(fā)布中...'); let self = this; let content = this.content; let param = new FormData(); param.append('content', content); param.append('username', this.userInfo._id); this.filesArr.forEach((file) => { param.append('file2', file); }); self.axios.post('/upload/uploadFile', param, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }).then(function (result) { console.log(result.data); self.$router.push({path: '/home'}); Indicator.close(); Toast(result.data.msg) }) }
后端通過multer模塊保存?zhèn)鬏數(shù)膱D片,再把保存下來的圖片發(fā)送到阿里云oss(這個可以根據(jù)自己的使用情況變化)
let filePath; let fileName; let Storage = multer.diskStorage({ destination: function (req, file, cb) {//計算圖片存放地址 cb(null, './public/img'); }, filename: function (req, file, cb) {//圖片文件名 fileName = Date.now() + '_' + parseInt(Math.random() * 1000000) + '.png'; filePath = './public/img/' + fileName; cb(null, fileName) } }); let upload = multer({storage: Storage}).any();//file2表示圖片上傳文件的key router.post('/uploadFile', function (req, res, next) { upload(req, res, function (err) { let content = req.body.content || ''; let username = req.body.username; let imgs = [];//要保存到數(shù)據(jù)庫的圖片地址數(shù)組 if (err) { return res.end(err); } if (req.files.length === 0) { new Pyq({ writer: username, content: content }).save().then((result) => { res.json({ result: result, code: '0', msg: '上傳成功' }); }) } /*client.delete('public/img/1.png', function (err) { console.log(err) });*/ let i = 0; req.files.forEach((item, index) => { let filePath = `./public/img/${item.filename}`; put(item.filename,filePath,(result)=>{ imgs.push(result.url); i++; if (i === req.files.length) { //forEach循環(huán)是同步的,但上傳圖片是異步的,所以用一個i去標記圖片是否全部上傳成功 //這時才把數(shù)據(jù)保存到數(shù)據(jù)庫 new Pyq({ content: content, writer: username, pimg: imgs }).save().then(() => { res.json({ code: '0', msg: '發(fā)布成功' }); }) } }) }) }) });
關于怎么在vue中使用node上傳圖片并預覽問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。