HTML
<input type="file" name="company_img_file" class="custom-file-input" id="inputGroupFile04" placeholder="上传营业执照图片" multiple>
JS绑定input change事件触发上传
$("input[name='company_img_file']").change(function(){
var fileArr = $("input[name='company_img_file']")["0"].files;
var fileArrLength = fileArr.length;
var uploadFile = [];
for (var i = 0; i < fileArrLength;i++) {
var reader = new FileReader();
reader.readAsDataURL(fileArr[i])
reader.onload = function(e,i) {
uploadFile.push(e.target.result)
if(uploadFile.length == fileArrLength){
$.ajax({
type:"post",
url:'/testUpload',
data:{company_img_file:uploadFile},
success:function(res){
console.log(res)
},
error:function(){
console.log('网络错误')
}
})
}
}
}
})
TP后台处理上传的图片
private function saveBase64Image($base64_image_content){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
//图片后缀
$type = $result[2];
//保存位置--图片名
$image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
$image_file_path = '/uploads/image/'.date('Ymd');
$image_file = ROOT_PATH.'public'.$image_file_path;
$imge_real_url = $image_file.'/'.$image_name;
$imge_web_url = $image_file_path.'/'.$image_name;
if (!file_exists($image_file)){
mkdir($image_file, 0700);
fopen($image_file.'\\'.$image_name, "w");
}
//解码
$decode=base64_decode(str_replace($result[1], '', $base64_image_content));
if (file_put_contents($imge_real_url, $decode)){
$data['code']=0;
$data['imageName']=$image_name;
$data['url']='https://'.$_SERVER['HTTP_HOST'].$imge_web_url;
$data['msg']='保存成功!';
}else{
$data['code']=1;
$data['imgageName']='';
$data['url']='';
$data['msg']='图片保存失败!';
}
}else{
$data['code']=1;
$data['imgageName']='';
$data['url']='';
$data['msg']='base64图片格式有误!';
}
return $data;
}
public function testUpload(){
$data = $this->request->post();
$base64 = $data['company_img_file'];
$arr = array();
foreach ($base64 as $key => $value) {
$arr[$key] = $this->saveBase64Image($value);
}
return json($arr);
}
返回结果