file upload laravel 5

2019-08-10 03:55发布

问题:

Hi I'm trying to upload an image with Laravel 5

Function is:

$file_name = '';
//validation of image before uploading and saving
if( Input::hasFile('img')  && Input::file('img')->isValid() ){
    $file = Input::file('img'); //creating an object
    $file_name = str_random(30) . '.' . $file->getClientOriginalExtension(); //randon str name to img file with the ext of the original file
    $file->move( public_path() . '\assets\img', $file_name);
}

form: multipart/form-data

input: input type="file" name="img"

The problem is that there's always an empty value in $file_name

回答1:

Your form opening tag should have enctype="multipart/form-data". Look like this:

<form method="POST" enctype="multipart/form-data">

And to move your image in storage, write your code in controller like this:

public function store(Request $request)
{
    if($request->hasFile('img') && $request->file('img')->isValid()){
        $file = $request->file('img');
        $file_name = str_random(30) . '.' . $file->getClientOriginalExtension();
        $file->move(base_path() . '/assets/img', $file_name);
    }
}