laravel上传图片

是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;

 }

}

Guess you like

Origin blog.csdn.net/weixin_51899618/article/details/121531897