<input type="file" name="pic1" id="pic" accept="image/gif,image/jpeg,image/x-png"/>
<script>
//上传图片
$('#pic').change(function(event) {
var formData = new FormData();
formData.append("file", $(this).get(0).files[0]);
$.ajax({
url:"..........",
type:'POST',
data:formData,
cache: false,
contentType: false, //不可缺
processData: false, //不可缺
success:function(data){
console.log(data)
//{code: 1, msg: "成功", photo: "upload/default/20180815/5b73c6fadfdf8.jpg"}
}
});
});
</script>
/**
* Ajax上传图片
*/
public function uploadPic(){
//接收文件
$file=request()->file('file');
if($file==null){
exit(json_encode(array(
'code'=>'error',
'msg'=>'请上传文件!'
)));
}
$filePaths= 'upload' . DS . 'default' . DS .date('Ymd',time());
if(!empty($file)){
$info = $file->validate(['size'=>10485760,'ext'=>'gif,jpg,jpeg,png,bmp,swf'])->rule('uniqid')->move($filePaths);
$error = $file->getError();
//验证文件后缀后大小
if(!empty($error)){
dump($error);exit;
}
if($info){
// 成功上传后 获取上传信息
$info->getSaveName();
$photo = $info->getSavename();
}else{
// 上传失败获取错误信息
$file->getError();
}
}else{
$photo = '';
}
if($photo !== ''){
return ['code'=>1,'msg'=>'成功','photo'=>$filePaths.DS.$photo];
}else{
return ['code'=>404,'msg'=>'失败'];
}
}