Vue上传图片

发布时间:2019-05-14 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue上传图片脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

最近写上传图片功能,一直不理解是怎么实现的,今天看了后端的接口实现,才知道大致流程。
后台接口接受一个input提交的文件,将其保存,并将文件名返回。将此返回的内容当做img标签的src即可,展示图片
(1)form表单实现
htML:

<form name="imgForm" id="imgForm" enctype="multipart/form-data" action="图片上传接口" method='post'>
    <input class="input-loc-img"  name="imgLocal" id="imgLocal" type='file' accept="image/*" @change="selectImg" />
</form> 
js:
selectImg(){
    let form=document.getElementById('imgLocal');
    form.submit();
}

(2)ajax实现(Vue推荐的axios)

let that=this;
let imgFile = $(this.$el).find('#imgLocal')[0].files[0];//取到上传的图片
console.LOG($(this.$el).find('#imgLocal')[0].files);//由打印的可以看到,图片    信息就在files[0]里面
let formData=new FormData();//通过formdata上传
formData.append('file',imgFile);
this.$http.post('图片上传接口',formData,{
method: 'post',
headers: {'Content-Type': 'multipart/form-data'}
}).then(function (res) {
console.log(res.data);//
}).catch(function(error){
console.log(error);
})

Vue上传图片

脚本宝典总结

以上是脚本宝典为你收集整理的Vue上传图片全部内容,希望文章能够帮你解决Vue上传图片所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。