1. 程式人生 > >vue實現圖片上傳

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>