首先 在./components/common/創(chuàng)建組件的vue文件imageUpload.vue
然后記得在components下的app.js注冊(cè)組件
Vue.component('image-upload', require('./components/common/imageUpload.vue'))
image-upload
就是組件名
imageUpload.vue 內(nèi)容為
<template>
<div class="columns">
<div class="column is-2">
<div class="field-label is-normal">
<label class="label">上傳圖片</label>
</div>
</div>
<div class="column is-10">
<div class="field-body">
<div class="field">
<div class="control">
<input type="hidden" name="uploadImg" :value="imagePath">
<input id="iphoneOpenCameraInput" class="is-hidden" type="file" accept="image/*" @change="uploadImg" ref="isUploadImg">
![](imgUrl)
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: { imagePath:String, imgUrl:String, uploadUrl:String },
methods: {
uploadImg(){
var self= this
var file=this.$refs.isUploadImg.files[0]
console.log(file)
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function () {
self.imgUrl=this.result
var postData={
imgUrl:this.result
}
self.$axios.post(self.uploadUrl,postData).then((response) => {
self.imagePath = response.data['imgPath'] }, (error) => {
console.log(error)
})
}
},
openUploadImages () {
this.$refs.isUploadImg.click();
},
}
}
</script>
注:上傳圖片的默認(rèn)圖片我這里放在了public下的image下缀去,可根據(jù)自己需要修改
這樣在引入時(shí)候直接調(diào)用<image-upload></image-upload>
就可以使用上傳組件了
寫好了組件 我們來(lái)看看怎么使用laravel去寫上傳部分的后端代碼
首先要在public文件下創(chuàng)建/upload/images的路徑存放圖片
下面看看后端的代碼:
public function imgUpload(Request $req) {
$uploadImg=$req->imgUrl;
$data=array();
$data['imagesPath']='';
$data['error']='';
$data['status']=1;
if($uploadImg){
$base64_body = substr(strstr($uploadImg, ','), 1);
$img = base64_decode($base64_body);
$path='upload/images/';
if(!file_exists($path)){
$data['error']='文件目錄不存在';
$data['status']=0;
}
$filename = $path. date('YmdHis', time()).rand(100000,999999) . '.jpg';
if (file_put_contents($filename, $img, FILE_APPEND)) {
$data['imagesPath']=url($filename);
} else {
fopen($filename, 'a+');
unlink($filename);
$data['error']='文件獲取失敗!';
$data['status']=0;
}
}
return $data;
}
返回的data就是我們的文件路徑了 你可以在這里上傳路徑到數(shù)據(jù)庫(kù)
最后在路由文件里面注冊(cè)這個(gè)方法 就可以在前端異步請(qǐng)求了