php+ajax文件上传
html:
<input id="user_real_name" class="input_show" type="text" value="" placeholder="姓名"> <input id="file1" class="ufile" type="file" name="file1" accept="image/gif,image/jpeg,image/jpg,image/png"> <input id="file2" class="ufile" type="file" name="file2" accept="image/gif,image/jpeg,image/jpg,image/png"> <input id="file3" class="ufile" type="file" name="file3" accept="image/gif,image/jpeg,image/jpg,image/png">
javascript:
var user_real_name = $("#user_real_name").val(); var fileObj1 = document.getElementById("file1").files[0]; // js 获取文件对象 var fileObj2 = document.getElementById("file2").files[0]; // js 获取文件对象 var fileObj3 = document.getElementById("file3").files[0]; // js 获取文件对象 var formFile = new FormData(); formFile.append("user_real_name",user_real_name); formFile.append("file1", fileObj1);//加入文件对象 formFile.append("file2", fileObj2);//加入文件对象 formFile.append("file3", fileObj3); //加入文件对象 $.ajax({ url:"/User/userUpdate", data:formFile, type:"post", dataType:"json", processData :false, // 不处理发送的数据,因为data值是Formdata对象,不需要对数据做处理 contentType :false, // 不设置Content-type请求头 success:function(data){ if(data.statusCode==200){ console.log("成功"); }else{ console.log("失败"); } $("input[type=file]").val(''); }, error:function(){ console.log("错误"); } });
php:
$data['user_real_name']=$_POST['user_real_name']; if(!empty($_FILES)){ //有文件上传时 $msg['img1']=''; $msg['img2']=''; $msg['img3']=''; if(!empty($_FILES['file1'])){ $file['file']=$_FILES['file1']; $url = ToolModel::UploadAws($file); //亚马逊云上传 $data["user_face_image"]=trim($url); //返回的文件路径 $msg['img1']=$data["user_face_image"]; } if(!empty($_FILES['file2'])){ $file['file']=$_FILES['file2']; $url = ToolModel::UploadAws($file); //上传 $data["user_back_image"]=trim($url); //返回的文件路径 $msg['img2']=$data["user_back_image"]; } if(!empty($_FILES['file3'])){ $file['file']=$_FILES['file3']; $url = ToolModel::UploadAws($file); //上传 $data["user_body_image"]=trim($url); //返回的文件路径 $msg['img3']=$data["user_body_image"]; } } $User = new UserModel(); $res =$User->userUpdate($uid,$data); //更新数据 if($res!==false){ $msg['statusCode']=200; $msg['msg']='上传成功'; $this->ajaxReturn($msg,'JSON'); }else{ $msg['statusCode']=1000; $msg['msg']='上传失败'; $this->ajaxReturn($msg,'JSON'); }