Daniel Pinzon
Daniel Pinzon

Reputation: 31

Display uploaded image using AJAX and Laravel

I want to display a thumbnail of the uploaded images without having to reload the page (AJAX).

Here is my Laravel Controller:

public function save(Request $request)
{
if (Input::hasFile('file'))
    {
        $file = $request->file('file');
        $name = $file->getClientOriginalName();
        Storage::disk('local')->put($name, File::get($file));
        $path = 'storage/files/';

        return response()->json(array('path'=> $path), 200);
    } else {
        return response()->json(false, 200);
    }
}

HTML View using Blade:

@foreach($lists as $item)
    <div style="float: left;">
       <img id="preview" src="{{ asset('storage/files/'.$item->name) }}" alt="" with="100" height="100">
    </div>
@endforeach

This displays the image when reloading, I want to display it without refreshing the website.

Upvotes: 0

Views: 1807

Answers (1)

Sreejith BS
Sreejith BS

Reputation: 1203

You don't need AJAX to display thumbnail of uploaded image. Change your form like this:

<img id="preview" src="{{ asset('storage/files/'.$item->name) }}" alt="" with="100" height="100">

<input type="file" name="image" style="display:none"; onchange="document.getElementById('preview').src = window.URL.createObjectURL(this.files[0])">

Upvotes: 0

Related Questions