Laravel - 使用存储上传图像时创建自定义名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43228902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - Create custom name while uploading image using storage
提问by Bachcha Singh
I am trying to upload a file using laravel Storage i.e
$request->file('input_field_name')->store('directory_name');
but it is saving the file in specified directory with random string name.
我正在尝试使用laravel Storage ie上传文件,
$request->file('input_field_name')->store('directory_name');
但它正在使用随机字符串名称将文件保存在指定目录中。
Now I want to save the uploaded file with custom namei.e current timestamp concatenate with actual file name. Is there any fastest and simplest way to achive this functionality.
现在我想用自定义名称保存上传的文件,即当前时间戳与实际文件名连接。有没有最快和最简单的方法来实现这个功能。
回答by Alexey Mezenin
回答by Sanchit Gupta
You can use below code :
您可以使用以下代码:
Use File Facade
使用文件外观
use Illuminate\Http\File;
use Illuminate\Http\File;
Make Following Changes in Your Code
在您的代码中进行以下更改
$custom_file_name = time().'-'.$request->file('input_field_name')->getClientOriginalName();
$path = $request->file('input_field_name')->storeAs('directory_name',$custom_file_name);
For more detail : Laravel FilesystemAnd storeAsas mention by @Alexey Mezenin
有关更多详细信息:Laravel 文件系统和存储正如@Alexey Mezenin 所提到的
Hope this code will help :)
希望这段代码会有所帮助:)
回答by Tonmoy Nandy
You also can try like this
你也可以这样试试
$ImgValue = $request->service_photo;
$getFileExt = $ImgValue->getClientOriginalExtension();
$uploadedFile = time()'.'.$getFileExt;
$uploadDir = public_path('UPLOAS_PATH');
$ImgValue->move($uploadDir, $uploadedFile);
Thanks,
谢谢,
回答by PHP Dev
Try with following work :
尝试以下工作:
$image = time() .'_'. $request->file('image')->getClientOriginalName();
$path = base_path() . '/public/uploads/';
$request->file('image')->move($path, $image);
回答by Asim Shahzad
You can also try this one.
你也可以试试这个。
$originalName = time().'.'.$file->getClientOriginalName();
$filename = str_slug(pathinfo($originalName, PATHINFO_FILENAME), "-");
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$path = public_path('/uploads/');
//Call getNewFileName function
$finalFullName = $this->getNewFileName($filename, $extension, $path);
// Function getNewFileName
public function getNewFileName($filename, $extension, $path)
{
$i = 1;
$new_filename = $filename . '.' . $extension;
while (File::exists($path . $new_filename))
$new_filename = $filename . '_' . $i++ . '.' . $extension;
return $new_filename;
}