基本上所有的电商网站都会用到上传图片的功能,上传一小段自己的demo希望对小伙伴们有点帮助~
需求:1、初始化时查询商品详情数据取出商品图片回显
2、点击“编辑”则上传相册图片或者拍照上传图片,上传的图片替换原来的图片
<template>
<div class="picture_upload">
<div class="img_up">
<div class="pic_b" v-show="disUpload">
<img :src="$imgBase + imgUrl" alt="" />
</div>
<div class="pic_b" v-show="!disUpload">
<img :src="$imgBase + detailData.headPic" alt="" />
</div>
<div class="footer_edit">
<div class="i_icon">
<img :src="$imgBaseUrl + '/common/edit.png'" alt="" />
</div>
<input
type="file"
name="file"
multiple
accept="image/*"
@change="update"
/>
</div>
</div>
</div>
</template>
<script>
import { upfile } from "@/http/goodsManagement"; //引入接口
export default {
name: "PictureUpload",
props:{
detailData:{
type:Object,
value:{}
}
},
data() {
return {
imgUrl: "",
disUpload:false,
};
},
methods: {
update(e) {
let file = e.target.files[0];
let Max_size=file.size;
console.log(file);
let param = new FormData(); //创建form对象
param.append("file", file, file.name); //通过append向form对象添加数据
e.target.value = ""; //置为空,解决再次上传同一张图片失效问题
this.uploadImg(param);
},
uploadImg(param) {
//调用上传图片接口将
upfile(param).then(res => {
if (res.code == 200) {
this.imgUrl = res.data;
this.disUpload = true;
this.$emit("uploadImg", res.data)
}
console.log(res);
}).catch((e)=>{
console.log(e)
});
}
}
};
</script>
<style lang="scss" scoped>
@mixin img_center {
display: flex;
justify-content: center;
align-items: center;
img {
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
}
}
.picture_upload {
width: 100%;
overflow: hidden;
.img_up {
width: 200px;
height: 200px;
margin: 40px auto;
position: relative;
border-radius: 12px;
.pic_b {
width: 200px;
height: 200px;
@include img_center;
img {
border-radius: 12px;
}
}
.footer_edit {
width: 200px;
height: 40px;
line-height: 40px;
background: rgba(0, 0, 0, 0.5);
border-radius: 0px 0px 12px 12px;
position: absolute;
bottom: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
input {
width: 100%;
height: 100%;
opacity: 0;
position: absolute;
top: 0px;
left: 0px;
}
.i_icon {
display: inline-block;
width: 76px;
height: 22px;
line-height: 22px;
img {
width: 100%;
height: 100%;
border-radius: 12px;
}
}
span {
font-size: 20px;
color: #fff;
}
}
}
}
</style>
打印的file
注意:接口的提交方式以from表单提交的方式, 请求头使用 headers: {‘Content-Type’:‘multipart/form-data’}
效果图如下: