技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機(jī)純凈版,64位旗艦版,綠色軟件,免費(fèi)軟件下載基地!

當(dāng)前位置:主頁 > 教程 > 服務(wù)器類 >

vue.js如何上傳圖片實(shí)例代碼

來源:技術(shù)員聯(lián)盟┆發(fā)布時(shí)間:2019-10-23 06:00┆點(diǎn)擊:

<div class="form-group"> <label>背景圖</label> <input type="file" class="form-control" @change="onFileChange"> </div> <div class="form-group" v-if="image"> <label>背景圖預(yù)覽</label> ![](image) </div>

vue.js部分

在methods里添加

onFileChange(e) { var files = e.target.files || e.dataTransfer.files; if (!files.length) return; this.createImage(files[0]); }, createImage(file) { var image = new Image(); var reader = new FileReader(); var vm = this; reader.onload = (e) => { vm.image = e.target.result; }; reader.readAsDataURL(file); },

那么提交時(shí)如何獲取呢?

在提交的方法里,通過 this.image 即可,獲取的圖片格式是圖片流格式,以data:image開頭。

如何在后端(我用php)獲取呢?

直接貼代碼

$bg = $request->get('image');//獲取圖片流 $url = explode(',',$bg); $filename = md5(time().str_random(8)).'.png';//自定義圖片名 $filepath = public_path('image').'http://www.3lian.com/'.$filename;//圖片存儲(chǔ)路徑 $bgurl = '/image/'.$filename;//圖片url ,具體看自己后臺(tái)環(huán)境,我用的是laravel file_put_contents($filepath, base64_decode($url[1]));//保存圖片到自定義的路徑

將$bgurl保存在數(shù)據(jù)庫即可。