最近写上传图片功能,一直不理解是怎么实现的,今天看了后端的接口实现,才知道大体流程。
后台接口接受一个input提交的文件,将其保存,并将文件名返回。将此返回的内容当作img标签的src便可,展现图片
(1)form表单实现
html: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)ios
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); })