将图片上传到 Laravel-Lumen API

4
使用我的API,我需要从移动应用程序上传图像到服务器并将图像路径保存到数据库中,因此我有以下问题:
  • Where to save the images? I tried to save them in the storage/app under images folder (which is work fine)

       public function fileUpload(Request $request) {
    
    
       if ($request->hasFile('image')) {
           $image = $request->file('image');
           $name = time().'.'.$image->getClientOriginalExtension();
           $destinationPath = storage_path('/app/images');
           $image->move($destinationPath, $name);
    
    
           return response()->json(['data'=>"image is uploaded"]);
       }
    

    }

    and make a symbolic link to this folder in the public folder but its not working due to access permission error which will lead to the other issue.

  • What permission should i gave to the storage folder to make the whole operation works save the images and the saved link is readable (even 777 didn't work) Access forbidden!

    sudo chmod -R 777 storage

非常感谢您提供的任何想法


你试过使用 755 吗? - freelancer
是的,也没有起作用。 - Mohammed Riyadh
尝试使用 chmod -R 0777 storage(注意 0777)。还可以尝试 php artisan storage:link - Tpojka
1
找不到“php artisan storage:link”命令。在“storage”命名空间中没有定义任何命令。 - Mohammed Riyadh
3个回答

3

存储目录不对用户请求开放,公共目录是可以的,您需要从存储目录到公共目录创建符号链接:

代码示例: ``` php artisan storage:link ```
此命令将在公共文件夹中创建一个指向存储文件夹的符号链接。这使得存储文件夹中的文件可以通过公共文件夹中的 URL 访问。

php artisan storage:link

这个命令将从public/storage创建一个符号链接到storage/app/public。这样,您可以将文件存储在storage/app/public中,并从Web上访问它。
$image = $request->file('image');
$image->storeAs('public', $name); // => storage/app/public/file.img
URL::asset('storage/'.$name); // => http://example.com/stoage/file.img

2
找不到“php artisan storage:link”命令。在“storage”命名空间中没有定义任何命令。 - Mohammed Riyadh
2
我认为Lumen不支持这个命令,它是Laravel的轻量级版本,你可能需要手动创建符号链接 ln -s storage/app/public public/storage 或者 你可以在public目录下创建一个名为images的文件夹,并将其所有者更改为Web服务器用户www-datachown -R www-data:your_user images,然后像这样将上传的文件存储在images目录下:$image->storeAs('images', $name); - YouneL
感谢您的回答和评论,问题在于Lumen中无法使用Filesystem函数,执行$image->storeAs('images', $name)时会抛出错误信息Target [Illuminate\Contracts\Filesystem\Factory] is not instantiable,而且在Lumen中也无法使用base_path()。这就是我询问关于最佳图像保存文件夹的原因。 - Mohammed Riyadh
对于Windows用户,这个链接展示了如何使用mklink命令手动创建符号链接。 - Nurkartiko

1
我建议你尝试在公共文件夹中创建一个文件夹,并将文件存储在那里。您可以使用base_path()."/public/uploads"。

0

存储图像的最佳位置应该是在 storage 文件夹中,并创建一个符号链接到 public 文件夹。

sudo chmod -R 777 storage 应该可以解决问题。确保您正在访问正确的 URL。

要访问图像,您应该使用类似下面的 URL。我的文件夹结构看起来像 /storage/app/public/images/user/avatar/

本地:http://localhost/project-name/public/storage/images/user/avatar/HdXzVnKxzUSdAssvXaoM2n0ixzEEG7jlK8acLiHV.png

生产环境:http://example.com/storage/images/user/avatar/3133L07guCv8shINNZM30c2Ux1HdfpFt04YdLRpf.png

您可以查看此代码片段以确定是否遗漏了某些内容:https://gist.github.com/danish-shaikh/9c328288a817309f93238c6b5d48ed7e


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接