vue实现图片上传

项目中用到的是上传头像,前端通过input[type="file"]来选择图片,给后端传递一个formData格式的数据,然后上传。代码如下:

我写了个组件,参数如下:

uploadType: 上传类型

width: 图片显示的宽度

height: 图片显示的高度

imgUrl: 如果之前有图片,图片的路径地址

getImgUrl: 在组件里上传成功之后,会得到图片路径的相关参数,该方法在父组件里面调用来获取子组件里返回的图片路径参数,这个事件要看需求,在父组件里需不需要上传之后返回的图片的相关路径,若不需要就不用写。

<upload :uploadType="`head`" :imgWidth="`85px`" :imgHeight="`104px`" :imgUrl="imgUrl"
@upload="getImgUrl"></upload>
//接收子组件emit的事件
getImgUrl(data) {
//data 得到的就是返回的图片路径的相关参数
}
//upload组件里的代码
<template>
<div class="avatar">
<div @mouseover="showBg=true" @mouseleave="showBg=false">
<div class="bg" v-if="showBg" :style="`line-height:${imgHeight}`">点击上传</div>
<input type="file" class="input-file" :style="`width:${imgWidth};height:${imgHeight};`" name="avatar" ref="avatarInput" @change="changeImage($event)" accept="image/gif,image/jpeg,image/jpg,image/png">
<img :src="avatar?avatar:require('../assets/images/man.png')" alt="" :style="`width:${imgWidth};height: ${imgHeight};`" name="avatar">
</div>
<div class="text" @click="upload" v-if="file">确定上传</div>
</div>
</template>
<script>
export default {
name: 'upload',
data(){
return{
avatar: '',
file: '',
showBg: false
}
},
props: ["uploadType", "imgUrl", "imgWidth", "imgHeight"],
created(){
this.avatar = this.imgUrl
},
methods: {
changeImage: function(e){
let file = e.target.files[0];
this.file = file
console.log(this.file)
let reader = new FileReader()
let that = this
reader.readAsDataURL(file)
reader.onload= function(e){
that.avatar = this.result
}
},
upload: function(){
if(this.$refs.avatarInput.files[0].length !== 0){
let data = new FormData();
data.append('multfile', this.$refs.avatarInput.files[0]);
data.append('operaType', this.uploadType);
this.$store.dispatch('UPLOAD_HEAD', data) //调用上传接口,把data传递给接口
.then(res => {
this.file = '';
let data = res.data.data;
//给父组件传递emit事件,把返回的图片路径相关参数传递过去
this.$emit("upload", data );
this.$message({
type: "success",
message: "上传成功!"
})
}).catch(err => {
console.log(err)
if(err.data.msg){
this.$message({
type: "error",
message: err.data.msg
})
}else {
this.$message({
type: "error",
message: "上传失败"
})
}
})
}
},
}
}
</script>
<style lang="less" scope>
.avatar {
cursor: pointer;
position: relative;
.input-file {
position: absolute;
top: 0;
left: 0;
opacity: 0;
cursor: pointer;
}
.bg {
width: 100%;
height: 100%;
color: #fff;
background-color: rgba(0,0,0,0.3);
text-align: center;
cursor: pointer;
position: absolute;
top: 0;
left: 0;

}
.text {
padding-top: 10px;
color: lightblue;
}
}
</style>

猜你喜欢

转载自www.cnblogs.com/yingjundeng/p/9928192.html