日常使用文件上传方式,都是通过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事件:
getFaceInfoFun(){ // 人脸采集
const requestId = curTimeFun(1,'-1') + Date.parse(new Date());
const param = {command: 'GetImage', requestId: requestId};
const _that = this;
$.ajax({
type: 'post',
data: JSON.stringify(param),
url: _that.deviceUrl,
success: function(data) {
let imgBase='data:image/gif;base64,' + JSON.parse(data).param.image;
let blob= dataURLtoFile(imgBase,'image/jpeg');
_that.submitPic(blob);
},
error: function(rsp) {
_that.$notify({title: '异常', message: "操作异常,请联系管理员", dangerouslyUseHTMLString: true, type: 'warning', duration: 0});
}
});
},
//将base64转换为blob
export function dataURLtoFile(dataURI, type) {
let binary = atob(dataURI.split(',')[1]);
let array = [];
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 }
// 图片提交事件。把bold格式转为formData格式进行提交。
submitPic(fileData){
let form = new FormData();
form.append("bizType","9");
let fileOfBlob = new File([fileData], new Date()+'.jpg'); // 重命名了
form.append("file", fileOfBlob);
// form.append("file",fileData); // 不重命名
const _that = this;
$.ajax({
type: 'post',
data:form,
url: _that.actionUrl,
processData:false,
contentType:false,
success: function(data) {
if(data.status == 200){
Vue.set(_that.form,'facePicPath',data.data);
} else {
_that.$notify({title: '异常', message: data.message, dangerouslyUseHTMLString: true, type: 'warning', duration: 0});
}
},
error: function(rsp) {
_that.$notify({title: '异常', message: "操作异常,请联系管理员", dangerouslyUseHTMLString: true, type: 'warning', duration: 0});
}
});
},
数据上传格式:
照片采集接口提交和响应:
照片上传接口接口提交和响应: