日常使用文件上传方式,都是通过input type='file'的文件选择框进行文件上传。但是会通过其他交互方式等到图片的base64格式进行上传。具体情况如下示意:
在项目开发中,需要进行照片采集,通过摄像头直接拍照采集到人脸数据,再上传到后台进行保存。照片采集插件,返回的人脸数据是base64格式的字符串,因此前端需要把图片数据转换为后台可以接收的方式进行上传。
1、照片采集接口返回数据格式。其中,param.image字段为接口返回的采集照片的base64数据格式。
command: "GetImageRet" param: { image: "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5P…………………………2Q==" status: 0}
requestId: "201905131557726753000"
页面代码:
<el-form-item label="人脸照路径" prop="facePicPath" style="width: 98%"> <el-input style="width: 80%;float: left;" :disabled="dialogStatus=='view'" v-model="form.facePicPath" placeholder="请输入人脸照路径"></el-input> <span style="width: 20%;float: left;">
<el-button @click="getFaceInfoFun('form')" style="background: #408FD8;color: #fff;border: 1px solid #408FD8;margin-left: 5px;">人脸采集</el-button> </span> </el-form-item>
JS事件:
1 getFaceInfoFun(){ // 人脸采集 2 const requestId = curTimeFun(1,'-1') + Date.parse(new Date()); 3 const param = {command: 'GetImage', requestId: requestId}; 4 const _that = this; 5 $.ajax({ 6 type: 'post', 7 data: JSON.stringify(param), 8 url: _that.deviceUrl, 9 success: function(data) { 10 let imgBase='data:image/gif;base64,' + JSON.parse(data).param.image; 11 let blob= dataURLtoFile(imgBase,'image/jpeg'); 12 _that.submitPic(blob); 13 }, 14 error: function(rsp) { 15 _that.$notify({title: '异常', message: "操作异常,请联系管理员", dangerouslyUseHTMLString: true, type: 'warning', duration: 0}); 16 } 17 }); 18 },
1 //将base64转换为blob 2 export function dataURLtoFile(dataURI, type) { 3 let binary = atob(dataURI.split(',')[1]); 4 let array = []; 5 for(let i = 0; i < binary.length; i++) { 6 array.push(binary.charCodeAt(i)); 7 } 8 return new Blob([new Uint8Array(array)], {type:type }); 9 }
1 // 图片提交事件。把bold格式转为formData格式进行提交。 2 submitPic(fileData){ 3 let form = new FormData(); 4 form.append("bizType","9"); 5 let fileOfBlob = new File([fileData], new Date()+'.jpg'); // 重命名了 6 form.append("file", fileOfBlob); 7 // form.append("file",fileData); // 不重命名 8 const _that = this; 9 $.ajax({ 10 type: 'post', 11 data:form, 12 url: _that.actionUrl, 13 processData:false, 14 contentType:false, 15 success: function(data) { 16 if(data.status == 200){ 17 Vue.set(_that.form,'facePicPath',data.data); 18 } else { 19 _that.$notify({title: '异常', message: data.message, dangerouslyUseHTMLString: true, type: 'warning', duration: 0}); 20 } 21 }, 22 error: function(rsp) { 23 _that.$notify({title: '异常', message: "操作异常,请联系管理员", dangerouslyUseHTMLString: true, type: 'warning', duration: 0}); 24 } 25 }); 26 },
数据上传格式:
照片采集接口提交和响应:
照片上传接口接口提交和响应: