一、逻辑
点击li触发事件chooseImage 即触发input标签事件photoChange
input标签事件photoChange
file返回的是如下变量
模拟上传表单方法
执行上传
二、代码
<li class="scroll-item first-item" @click="chooseImage"> <i class="iconPhoto"></i> <span class="title">拍照</span> <input @change="photoChange($event)" type="file" id="upload_file" multiple style="display: none"/> </li>
chooseImage(){ document.getElementById(‘upload_file‘).click(); //触发input-file文件上传控件 事件photoChange }, photoChange(el) { var file = el.target.files[0];//name: "dangqi1.png" || type: "image/png" var type = file.type.split(‘/‘)[0]; if ( type === ‘image‘ ){ //将图片img转化为base64 var reader = new FileReader(); reader.readAsDataURL(file); var that = this; reader.onloadend = function () { var dataURL = reader.result; var blob = that.dataURItoBlob(dataURL); that.upload(blob); //执行上传接口 }; }else{ alert(‘上传了非图片‘); } }, dataURItoBlob (dataURI) { // base64 解码 let byteString = window.atob(dataURI.split(‘,‘)[1]); let mimeString = dataURI.split(‘,‘)[0].split(‘:‘)[1].split(‘;‘)[0]; let T = mimeString.split(‘/‘)[1]; let ab = new ArrayBuffer(byteString.length); let ia = new Uint8Array(ab); for (let i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ab], {type: mimeString}); }, upload(imgUrl){
let formData = new FormData();
formData.append(‘file‘, file);
this.$axios({
method:‘POST‘,
url:‘路径‘,
headers: {
‘Content-Type‘:‘multipart/form-data‘,//设置请求头请求格式为JSON
},
data: formData
}).then((response)=>{
console.log("response",response);
});
},