thinkphp5图片上传接口
public function avatarUpload() { $file = request()->file('file'); $filePath = 'avatar'; $width = 200; $height = 200; if($file){ $filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS .$filePath; if(!file_exists($filePaths)){ mkdir($filePaths,0777,true); } $info = $file->move($filePaths); if($info){ $imgpath = $filePaths . '/' . $info->getSaveName(); $image = \think\Image::open($imgpath); $image->thumb($width, $height)->save($imgpath); $imgpath = '/uploads/'.$filePath.'/'.$info->getSaveName(); $data = [ 'domain' => $_SERVER['HTTP_HOST'], 'filepath' => $imgpath, ]; return ['code' => 0, 'data' => $data, 'msg' => '上传成功']; }else{ // 上传失败获取错误信息 return ['code' => -1, 'data' => '', 'msg' => '上传失败']; } } }
<!DOCTYPE html> <html> <head> <title> </title> <script src="js/jquery-2.1.1.min.js" type="text/javascript"></script> </head> <body> <input type="file" name="file" onchange="fileup(event)"/> <script type="text/javascript"> function fileup(e){ var formData = new FormData(); formData.append('file', e.target.files[0]); $.ajax({ url: 'http://xxxxx.com/api/User/avatarUpload', type: 'POST', cache: false, data: formData, processData: false, contentType: false }).done(function(res) { console.log(res.data.domain); console.log(res.data.filepath); }).fail(function(res) { }); } </script> </body> </html>