7

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.

5 Answers 5

23

Use storeAs() instead:

$request->file('input_field_name')->storeAs('directory_name', time().'.jpg');
1
  • @AlexeyMezenin, working fine and thank you for quick reply. Commented Apr 5, 2017 at 11:04
6

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

0
3

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,

1
  • This is really a simplest way to save file inside public directory :) But I think @BachchaSingh want to achieve this using default Storage. +1 for suggesting the easiest way. Happy Coding :) Commented Apr 5, 2017 at 11:01
2

Try with following work :

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

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;

    }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.