使用laravel和vue.js制作一个上传图片的组件

首先 在./components/common/创建组件的vue文件imageUpload.vue
然后记得在components下的app.js注册组件

Vue.component('image-upload', require('./components/common/imageUpload.vue'))

image-upload就是组件名

imageUpload.vue 内容为
<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>

注:上传图片的默认图片我这里放在了public下的image下,可根据自己需要修改
这样在引入时候直接调用<image-upload></image-upload>就可以使用上传组件了

写好了组件 我们来看看怎么使用laravel去写上传部分的后端代码
首先要在public文件下创建/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就是我们的文件路径了 你可以在这里上传路径到数据库

最后在路由文件里面注册这个方法 就可以在前端异步请求了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 来源:github.com Vue.js开源项目速查表:https://www.ctolib.com/cheats...
    zhangtaiwei阅读 11,683评论 1 159
  • 转载 :OpenDiggawesome-github-vue 是由OpenDigg整理并维护的Vue相关开源项目库...
    果汁密码阅读 23,211评论 8 124
  • UI组件element ★11612 - 饿了么出品的Vue2的web UI工具套件 Vux ★7503 - 基于...
    董董董董董董董董董大笨蛋阅读 8,596评论 6 123
  • 懵懵懂懂,跌跌撞撞,一脚踏进来,抬头四顾,讶然,欣喜,又惴惴不安,原来你在这里呀!2017.8.6号于孟州。
    七月彭鹏阅读 221评论 0 0
  • 气节操守,是做人的标准,是检验灵魂的试金石。具有高尚节操者,诚信无欺,见义勇为,甚至舍生取义。他们能做到:“富贵不...
    有訶卟薖阅读 451评论 0 0