简体   繁体   中英

Laravel 5 : the move() function doesn't save the uploaded image file

What I'm trying is to set an image uploader with Laravel 5.

Here is the form.

    <form action="/edit/{{$id}}" method="POST" enctype="multipart/form-data">
        {!! csrf_field() !!}
        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
        <input type="hidden" name="_method" value="PUT">
            //There are other tags (including other input) here
            <input type="file" name="pic" accept="image/*">
        <input type="submit" value="Apply Changes">
    </form>

Here is the controller function which will be run from the form above.

public function update($id)
{
    $this->model->find($id)->fill($this->request->all())->save();
    if ($this->request->hasFile('pic')) {
        $file = $this->request->file('pic');
        $name = $file->getClientOriginalName();
        $file->move('assets/serviceimages/', $name);
    }

    return redirect('/blahblah');
}

As you might have noticed, this doesn't store the uploaded file under the assets/serviceimages/ directory, which is what I've been trying.

Basically I've been following this tutorial , but apparently I'm missing something and totally clueless about what it is, even after I had a look at the API documentation .

Inside of the if statement of the controller function, it was confirmed that the $file and $name had what I expected.

Therefore, I suspect that the problem lies in the move() function.

Any small piece of advice will be appreciated, since this is my first time that I've tried to set an uploader.

Permissions if you are on Linux. If that doesn't work try it this way:

$image = $request->file('pic');
$destinationPathImg = '/your path/images/';

if (!$image->move($destinationPathImg, $image->getClientOriginalName())) {
    return 'Error saving the file.';
}

Also, this need to be added in ur ()

public function update(Request $request, $id)

I found having to use the Storage adapter to use the full file path worked for me.

$storageAdapter = Storage::disk('v1')->getDriver()->getAdapter()

$full_path_before = $storageAdapter->applyPathPrefix($oldPath);
$full_path_after = $storageAdapter->applyPathPrefix($newPath);

if (!File::exists($full_path_before)){
   throw new \Exception("Error moving folders");
}
$move_files = $full_path_after !== $full_path_before;

if ($move_files){
   File::move($full_path_before, $full_path_after);
}

Use This Method This Will Work 100%

if($request->hasFile('filename')){

     $file = $request->filename;

    $file_new_name =  $file->move("upload/posts/", $file->getClientOriginalName());

    $post->filename = $file_new_names;

   }

Remember filename is your < img name="filename" >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM