简体   繁体   中英

Laravel - Create custom name while uploading image using storage

I am trying to upload a file using laravel Storage ie $request->file('input_field_name')->store('directory_name'); but it is saving the file in specified directory with random string name.

Now I want to save the uploaded file with custom name ie current timestamp concatenate with actual file name. Is there any fastest and simplest way to achive this functionality.

使用storeAs()代替:

$request->file('input_field_name')->storeAs('directory_name', time().'.jpg');

You can use below code :

Use File Facade

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 Filesystem And storeAs as mention by @Alexey Mezenin

Hope this code will help :)

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,

Try with following work :

 $image =  time() .'_'. $request->file('image')->getClientOriginalName();   
 $path = base_path() . '/public/uploads/';
 $request->file('image')->move($path, $image);

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;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM