Bachcha Singh
Bachcha Singh

Reputation: 3934

Laravel - Create custom name while uploading image using storage

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.

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

Upvotes: 7

Views: 22266

Answers (5)

PHP Dev
PHP Dev

Reputation: 503

Try with following work :

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

Upvotes: 2

Asim Shahzad
Asim Shahzad

Reputation: 1609

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;

    }

Upvotes: 1

Tonmoy Nandy
Tonmoy Nandy

Reputation: 381

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,

Upvotes: 3

Sanchit Gupta
Sanchit Gupta

Reputation: 3224

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 :)

Upvotes: 6

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Use storeAs() instead:

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

Upvotes: 23

Related Questions