1. 配置文件
设置上传的路径
对应文件夹
2. 前端
<div class="card-body"><h1 class="card-title">用户头像</h1><img src="../../../uploads/{$user.avatar_photo_path}" alt="avatar" height="100"/><form class="forms-sample" action="保存路径" method="post" enctype="multipart/form-data">选择图片(最大0.5M,格式jpg,jpeg,png):<input type="file" name="user_avatar_image"/> <button type="submit" class="btn btn-primary mr-2">上传</button></form>
</div>
3. 后端
/*** 保存用户头像*/function do_save_user_avatar()
{// 字段名$field_name = 'user_avatar_image';if(request()->isPost()){try {// 获取表单上传文件 例如上传了001.jpg$file = request()->file($field_name);// 使用验证器验证上传的文件validate(['file' => [// 限制文件大小(单位b),这里限制为1M'fileSize' => 0.5 * 1024 * 1024,// 限制文件后缀,多个后缀以英文逗号分割'fileExt' => 'jpg,jpeg,png']])->check(['file' => $file]);// 上传到本地服务器// public/uploads文件夹下的profile文件夹$save_name = \think\facade\Filesystem::disk('public')->putFile('profile', $file);if($save_name){// 要更新的数据库// // 上传之后的操作return $this->success('上传成功', '跳转路径');}} catch (\Throwable $e) {return $this->error('上传图片失败,' . $e->getMessage());}}}
注意:try catch中捕捉错误,是\Throwable $e
也可单独封装出一个上传文件的函数
/*** 上传文件* $field_name = 'user_avatar_image';* $subdirectory public下的哪个子目录* $fileSize = 0.5 (单位为M)* $fileExt 文件格式字符串*/function uploadFile($field_name, $subDirectory, $fileSize = 1, $fileExt = 'jpg,jpeg,png')
{// 获取表单上传文件 例如字段名是'user_avatar_image'if(!array_key_exists($field_name, $_FILES)){$response = [];$response['code'] = 100;$response['msg'] = 'FILES中不存在该变量';$response['data'] = [];return $response;}else{ // 变量'user_avatar_image'没有值if($_FILES[$field_name]['error'] != 0){$response = [];$response['code'] = 200;$response['msg'] = '没有上传文件';$response['data'] = [];return $response;}}if(request()->isPost()){try {// 获取表单上传文件 例如上传了001.jpg$file = request()->file($field_name);// 使用验证器验证上传的文件validate(['file' => [// 限制文件大小(单位b),这里限制为1M'fileSize' => $fileSize * 1024 * 1024,// 限制文件后缀,多个后缀以英文逗号分割'fileExt' => $fileExt]])->check(['file' => $file]);// 上传到本地服务器// uploads文件夹下的profile文件夹$save_name = \think\facade\Filesystem::disk('public')->putFile($subDirectory, $file);if($save_name){$response = [];$response['code'] = 1;$response['msg'] = '上传成功';$response['data'] = [];return $response;}} catch (\Throwable $e) {$response = [];$response['code'] = 300;$response['msg'] = '上传失败,' . $e->getMessage();$response['data'] = [];return $response;}}$response = [];$response['code'] = 400;$response['msg'] = '上传失败,非POST请求';$response['data'] = [];return $response;}
上传成功之后,如图
by 软件工程小施同学