【发布时间】: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;
}
除了上传目录外,它们完全相同。 我怎样才能使它成为整个应用程序的一个代码块,并根据表单更改文件名和位置?
一些文件名需要随机字符串,我怎样才能将随机字符串“编辑”到上传的文件中?
【问题讨论】:
-
使用 Spatie 媒体库 spatie.be/docs/laravel-medialibrary/v10/introduction