Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 820
Bachcha Singh Avatar asked Apr 05 '17 10:04

Bachcha Singh


5 Answers

Use storeAs() instead:

$request->file('input_field_name')->storeAs('directory_name', time().'.jpg');
like image 194
Alexey Mezenin Avatar answered Oct 17 '22 01:10

Alexey Mezenin


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

like image 37
Sanchit Gupta Avatar answered Oct 17 '22 03:10

Sanchit Gupta


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,

like image 39
Tonmoy Nandy Avatar answered Oct 17 '22 01:10

Tonmoy Nandy


Try with following work :

 $image =  time() .'_'. $request->file('image')->getClientOriginalName();   
 $path = base_path() . '/public/uploads/';
 $request->file('image')->move($path, $image);
like image 2
PHP Dev Avatar answered Oct 17 '22 03:10

PHP Dev


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;

    }
like image 1
Asim Shahzad Avatar answered Oct 17 '22 02:10

Asim Shahzad