【问题标题】:Laravel 8 image upload: Best practices for storing and editing image filesLaravel 8 图片上传:存储和编辑图片文件的最佳实践
【发布时间】:2023-02-19 14:16:31
【问题描述】:

我需要帮助来更好地理解这个概念,这样我才能成为更好的开发人员。我想学习如何重构代码并删除所有重复项。

图片上传的最佳做法是什么?正确重命名它们?

我有一段代码可以处理两个附件:

if( $request->hasFile('LFImage') ) {
            $destination = public_path('app/lostFound/lostItems' . $lostFound->LFImage);
            if( File::exists($destination) )
            {
                File::delete($destination);
            }
            $file = $request->file('LFImage');
            $extension = $file->getClientOriginalExtension();
            $filename = $lostFound->LFNumber . '-' . $lostFound->lostItem . '.' . $extension;
            $file->move('app/lostFound/lostItems', $filename);
            $lostFound->LFImage = $filename;

        }
        if( $request->hasFile('handoverStatement') ) {
            $destination = public_path('app/lostFound/handoverStatements' . $lostFound->handoverStatement);
            if( File::exists($destination) )
            {
                File::delete($destination);
            }
            $file = $request->file('handoverStatement');
            $extension = $file->getClientOriginalExtension();
            $filename = $lostFound->lostItem . '-' . $lostFound->LFNumber . '.' . $extension;
            $file->move('app/lostFound/handoverStatements', $filename);
            $lostFound->handoverStatement = $filename;
        }

除了上传目录外,它们完全相同。 我怎样才能使它成为整个应用程序的一个代码块,并根据表单更改文件名和位置?

一些文件名需要随机字符串,我怎样才能将随机字符串“编辑”到上传的文件中?

【问题讨论】:

标签: php laravel


【解决方案1】:

在 Laravel 中上传和存储文件的最佳实践是使用 Storage

它具有处理文件所需的所有方法,您可以像这样保存文件:

use IlluminateSupportFacadesStorage;
Storage::put('images/', $request->file('LFImage'));

在上面提供的文档中,您可以找到其他示例,例如重命名和移动文件

为了也可以从 Web 访问这些文件,您可以使用命令 php artisan storage:link,它会在您的公共文件夹中创建一个指向存储文件夹的符号链接。创建符号链接后,您可以生成文件的 URL,如下所示:

asset('storage/test.txt')

为避免重复,您可以在控制器中创建一个函数来创建文件。然后,您只需使用不同的文件调用此函数,即可将文件创建代码保存在一个地方。

【讨论】:

    【解决方案2】:

    你可以简单地写这个

    if ($request->hasFile('logo')) {
        deleteImageFromDirectory(setting('logo'), "Settings");
        $data['logo'] =  uploadImageToDirectory( $request->logo , "Settings");
    }
    

    并在您的辅助函数中定义 uploadImageToDirectory 函数或创建特征

    function uploadImageToDirectory($imageFile, $directory = '' ){
       $imageName = $imageFile->getClientOriginalName();  // Set Image name
       $imageFile->storeAs("/Images/$directory", $imageName, 'public');
       return $imageName;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 1970-01-01
      • 2013-06-26
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      相关资源
      最近更新 更多