beginner
beginner

Reputation: 2032

Laravel upload image in the Public Folder not in Storage Folder

I want the uploaded file to be located in the public/uploads folder directly like public/uploads/my_file.jpeg. Why is it that my code uploads it to public/uploads/file_name/file.jpeg?

here is the filesystems.php.

    'public_uploads' => [
        'driver' => 'local',
        'root'   => public_path() . '/uploads',
    ],

and here is the controller.

function upload_template(Request $request)
{


    $filee = $request->file('file_upload');
    $file_ext = $filee->extension();

    $file_name = $model->id . "." . $file_ext;

    Storage::disk('public_uploads')->put($file_name, $filee);

}

Upvotes: 0

Views: 1148

Answers (3)

STA
STA

Reputation: 34678

This happened because you specify the directory to store as filename. The file_name, should be the directory name such as images.

Refer to this line :

Storage::disk('public_uploads')->put($file_name, $filee);

So you could change this to :

Storage::disk('public_uploads')->put('images', $filee);
// output : /images/234234234.jpg

You need to provide the file contents in the second argument not file object, try this :

Storage::disk('public_uploads')->put($file_name, file_get_contents($filee));

To specific the file name you can use move() method instead of storage() :

if($request->hasFile('file_upload'))
{
  $filee = $request->file_upload;
  $name = "my_file"; // name here
  $fileName = $name . $filee->getClientOriginalName();
  $filee->move('public_uploads',$fileName);
}

Upvotes: 4

beginner
beginner

Reputation: 2032

I just found it Laravel 5.3 Storage::put creates a directory with the file name.

Need to provide the file contents in the second argument not file object. Tt should be Storage::disk('public_uploads')->put($file_name, file_get_contents($filee));.

Upvotes: 0

kadiro
kadiro

Reputation: 1116

//this is the best way you create a trait with 2 functions saveImage and 
//deleteImage

 public function saveImage($name,$folder){
$extention=$name->getClientOriginalExtension();
$filename=time().'.'.$extention;
$path=public_path().'/'.$folder;
$name->move($path,$filename);
return $filename;

}

public function deleteImage($name,$folder){
$image_path=public_path().'/'.$folder.'/'.$name;
unlink($image_path);

}

  function upload_template(Request $request){
    $file = $request->file_upload;//$request->your input name
     $img=$this->saveImage($file,'uploads');

     //you can use $img for storing the image in database for example 
      User::create([
        'avatar'=>$img
       ])
 }
//don't forget to invoke your trait

Upvotes: 0

Related Questions