Search code examples
phplaravellaravel-5

How to display a new image right away after successfully uploaded?


enter image description here

I implemented a logo upload system. It would take effect right away. It require me to refresh the page to see the effect. I'm wondering how do I stop that.

IMG

<img id="userLogo" src="/images/account/operator/logo.png" alt="" class="thumbnail img-responsive">

Form

{!! Form::open(array('url' => '/profile/logo/update', 'class' => 'form-horizontal', 'role' =>'form','id' => 'editLogo','files'=>true)) !!}

<input name="logo_path" type="file"> <br><br>

 <button class="btn btn-success btn-sm mr5" type="file"><i class="fa fa-user"></i> Update Logo</button>

{{ csrf_field() }}
{!! Form::close();!!}

Controller

public function updateLogo(){

    $inputs = Input::all();
    $logo_path = array('logo_path' => Input::file('logo_path'));

    $rule =  ['logo_path' => 'max:100|mimes:jpeg,bmp,png'];

    $id = Auth::user()->account_id;
    $type = Auth::user()->account_type;

    $validator = Validator::make($logo_path, $rule );

    if ( $validator->fails()) {
        return Redirect::to('/profile/')->withErrors($validator)->withInput();
    } else {

        $old_logo_path        = public_path().'/images/account/operator/logo.png';
        $delete = File::delete($old_logo_path);

        if (Input::hasFile('logo_path'))
        {

            $file            = Input::file('logo_path');
            $destinationPath = public_path().'/images/account/operator/';
            $uploadSuccess   = $file->move($destinationPath, 'logo.png');

        }

        return Redirect::to('/profile/')
        ->with('success','Your company logo was updated succesfully!');

    }
}

Result

My file got saved to the place I want them to be. But when the old logo is still showing on the page unless I refresh the page, then I'll see my new one.


Solution

  • This is because the image is cached in browser, and since you are updating an image with same name browser shows the already cached image. hence the better and effective solution is to have a unique file name every time you upload an image or you can append a querystring to the image path every time you serve an image.

    <img id="userLogo" src="/images/account/operator/logo.png?q=<?php echo microtime(); ?>" alt="" class="thumbnail img-responsive">