近来写上传图片功用,一向不理解是怎样完成的,本日看了后端的接口完成,才晓得大抵流程。
背景接口接收一个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);
})