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


发布了43 篇原创文章 · 获赞 10 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/cfun_goodmorning/article/details/79085757