Laravel:如何将图片完整访问URL存入数据库
如何将图片完整访问URL存储到数据库?
嘿,我来帮你搞定这个问题!你现在存储的是服务器端的相对路径,要改成带域名的完整可访问URL其实很简单,结合Laravel的特性就能轻松实现,下面是具体的步骤和修改后的代码:
前提准备
- 先检查你的
.env文件,确保APP_URL配置正确,比如APP_URL=https://abc.com,这是生成完整URL的核心基础 - 确保已经执行过
php artisan storage:link命令,创建public/storage到storage/app/public的符号链接——这是Laravel让前端能访问storage目录下文件的必要操作
修改上传代码
你只需要在存储文件后,把相对路径转换成完整URL再存入数据库即可,修改后的代码如下:
if(Input::file('profile_picture')) { $profilepic = Input::file('profile_picture'); $filename = time() . '.' . $profilepic->getClientOriginalExtension(); // 存储文件,返回相对于storage/app的路径(比如public/images/user/profile/12345.jpg) $relativeStoragePath = $request->file('profile_picture')->storeAs('public/images/user/profile', $filename); // 方法1:手动拼接完整URL // 把开头的public/替换成storage/,得到前端可访问的相对路径 $webAccessPath = str_replace('public/', 'storage/', $relativeStoragePath); // 拼接域名和访问路径,得到完整URL $fullImageUrl = config('app.url') . '/' . $webAccessPath; // 方法2:用Laravel自带的asset()方法(更简洁) // $fullImageUrl = asset($webAccessPath); // 方法3:用Storage类的url方法 // $fullImageUrl = config('app.url') . Storage::url($relativeStoragePath); // 最后把$fullImageUrl存入你的数据库字段即可 }
代码说明
storeAs()返回的是文件在storage/app下的相对路径,比如public/images/user/profile/xxx.jpg- 我们需要把
public/替换成storage/,因为符号链接指向的是storage/app/public,前端访问路径是/storage/xxx - 用
config('app.url')读取.env里配置的域名,和访问路径拼接后就是完整的可访问URL,比如https://abc.com/storage/images/user/profile/12345.jpg
这样存到数据库里的就是直接能访问的完整URL啦!
内容的提问来源于stack exchange,提问作者Javed
相关产品推荐
相关产品推荐

