【发布时间】:2019-11-24 01:40:46
【问题描述】:
我正在构建一个仅 laravel 5.8 API 的应用程序,并希望将图像路径作为 API 资源的路径返回,以便可以在图像源属性中使用它。所以这就是我必须做的来实现这一点。
1.我运行php artisan storgae:link命令创建从public/storage到storage/app/public的符号链接
- 首先,当像这样成功创建新产品时,我将图像存储在
productImages表中
public function store(Request $request)
{
// create & store the product
if ($product = Product::create([
'name' => $request->name,
'category' => $request->category,
'status' => $request->status,
'price' => $request->price,
'interest' => $request->interest,
])) {
// store the product image
$file = $request->file('image');
$destinationPath = "public/images/products";
$filename = 'pramopro_' . $product->name . '_' . $product->id . '.' . $file->extension();
Storage::putFileAs($destinationPath, $file, $filename);
ProductImage::create([
'product_id' => $product->id,
'name' => $filename
]);
}
// return new product
return new ProductResource($product);
}
- 像这样返回 ProductResource 中的图片路径
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'category' => $this->category,
'status' => $this->status,
'price' => $this->price,
'interest' => $this->interest,
'hidden' => $this->hidden,
'imageUrl' => asset('images/products/' . $this->image->name)
];
}
在我的本地服务器上测试它,我得到了这样的路径
{
"id": 1,
"name": "dpk",
"category": "fuel",
"status": "open",
"price": 100000,
"interest": 0.2,
"hidden": 0,
"imageUrl": "http://localhost:8000/images/products/pramopro_dpk_1.jpeg"
}
当我尝试通过在浏览器中输入http://localhost:8000/images/products/randomtext_1.jpeg 来查看图像时,我收到404 not found 错误。
但是这个http://localhost:8000/storage/images/products/pramopro_dpk_1.jpeg 按预期显示图像。
我应该如何检索图像路径以使其正常工作?
【问题讨论】: