当前位置:主页 > 软件编程 > PHP代码 >

laravel实现上传图片的两种方式小结

时间:2020-10-10 22:23:35 | 栏目:PHP代码 | 点击:

第一:是laravel里面自带的上传方式(写在接口里面的)

function uploadAvatar(Request $request)
 {
  $user_id = Auth::id();
  $avatar = $request->file('avatar')->store('/public/' . date('Y-m-d') . '/avatars');
  //上传的头像字段avatar是文件类型
  $avatar = Storage::url($avatar);//就是很简单的一个步骤
  $resource = Resource::create(['type' => 1, 'resource' => $avatar, 'user_id' => $user_id]);
  if ($resource) {
   return $this->responseForJson(ERR_OK, 'upload success');
  }
 return $this->responseForJson(ERR_EDIT, 'upload fails');
 }

第二:通用的上传方式

function upload_img($file)
{
 $url_path = 'uploads/cover';
 $rule = ['jpg', 'png', 'gif'];
 if ($file->isValid()) {
  $clientName = $file->getClientOriginalName();
  $tmpName = $file->getFileName();
  $realPath = $file->getRealPath();
  $entension = $file->getClientOriginalExtension();
  if (!in_array($entension, $rule)) {
   return '图片格式为jpg,png,gif';
  }
  $newName = md5(date("Y-m-d H:i:s") . $clientName) . "." . $entension;
  $path = $file->move($url_path, $newName);
  $namePath = $url_path . '/' . $newName;
  return $path;
 }
}

您可能感兴趣的文章:

相关文章