需求
最近做项目需要用到提交照片墙,本来项目使用的是element-ui的上传图片组件,后来考虑到优化问题,觉得没有必要为了一个上传引入如此大的UI库,因此考虑使用原生的方法来实现图片上传功能。
实现
准备
由于项目需要用到弹框以及toast等功能,因此改用了一个轻量级的UI库———vant,具体使用方法请看vant官方文档,接下来话不多说,直接上代码
HTML
<div id="pict">
<div class="icon-po" v-for="(item,index) in img">
<img :src="item" >
<div class="icon-close" @click="imgclose(index)">×</div>
</div>
<van-uploader :after-read="onRead" accept="image/jpg, image/jpeg" multiple class="icon-add">
</van-uploader>
</div>
复制代码
van-uploader是vant库里的上传图片组件,after-read是读取完成后的回调函数,我这里懒得重写css样式就直接引入了,使用<input type='file'/>
的onchange属性也可以实现同样的功能。
JS
data(){
return{
img:[],
}
},
methods:{
onRead(e){
//注意,我们这里没有使用form表单提交文件,所以需要用new FormData来进行提交
let fd= new FormData();
fd.append("upfile", e.file);//第一个参数字符串可以填任意命名,第二个根据对象属性来找到file
axios.post(url, {params:fd}) //url是服务器的提交地址
//成功回调
.then(res => {this.img.push(res.data.imgpath); }) //将服务器返回的图片链接添加进img数组,进行预览展示
//失败回调
.catch(err => {alert(err);});
};
},
//删除预览图片按钮
imgclose(e){
this.img.splice(e,1);
}
}
复制代码
CSS
.icon-add{
width: 200px;
height: 200px;
border: 1px dashed #9a9ba3;
overflow: hidden;
display: flex;
margin-top: 20px;
}
.icon-add:before{
content: '';
position: absolute;
width: 50px;
height: 2px;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -1px;
background-color: #aaabb2;
}
.icon-add:after{
content: '';
position: absolute;
width: 2px;
height: 50px;
left: 50%;
top: 50%;
margin-left: -1px;
margin-top: -25px;
background-color: #aaabb2;
}
.icon-po{
position: relative;
width: 200px;
height: 200px;
margin-right: 20px;
margin-top: 20px;
}
.icon-close{
position: absolute;
right: 5%;
top: 5%;
width: 30px;
height:30px;
border-radius: 50%;
background-color:red;
color: #fff;
font-size: 12px;
display: flex;
align-items: center;
justify-content: center;
}
复制代码
最终效果
小结
前段input提交图片文件通常使用两种方式,一种是form表单提交,还有一种是formData。