jQuery AJAX Uploader For Laravel
- Article
- Comment
jQuery AJAX uploader for laravel site and we are going to use simple HTML form and uploading image and show a preview on the upload form.
Lets start write coding, First begin with Routes.
Route::get('files', 'ImageController@getUploadForm'); Route::post('/files/image','ImageController@postUpload');
The above one help you to create the folder and path to images directory. Than move to the view file and create the form for the image uploader and preview.
<div class="row"> <div class="span8"> <h4>Ajax Image Upload and Preview With Laravel</h4> </div> </div> <!-- Post Footer --> <div class="row"> <div class="span3"> <div id="validation-errors"></div> <form class="form-horizontal" id="kv_upload" enctype="multipart/form-data" method="post" action="{{ url('files/image') }}" autocomplete="off"> <input type="hidden" name="_token" value="{{ csrf_token() }}" /> <input type="file" name="image" id="kv_image" /> </form> </div> <div class="span5"> <div id="output" style="display:none"> </div> </div> </div>
This is a sample form with AJAX support. and now we need to create a controller class to perform upload and storing operations.
<?php class ImageController extends BaseController { public function getUploadForm() { return View::make('image/upload-form'); } public function postUpload() { $file = Input::file('image'); $input = array('image' => $file); $rules = array( 'image' => 'image'); $validator = Validator::make($input, $rules); if ( $validator->fails() ){ return Response::json(['success' => false, 'errors' => $validator->getMessageBag()->toArray()]); } else { $destinationPath = 'files/'; $filename = $file->getClientOriginalName(); Input::file('image')->move($destinationPath, $filename); return Response::json(['success' => true, 'file' => asset($destinationPath.$filename)]); } } }
And finally , the Js function to handle the AJAX operations.
function showRequest(formData, jqForm, options) { jQuery("#validation-errors").hide().empty(); jQuery("#output").css('display','none'); return true; } function showResponse(response, statusText, xhr, $form) { if(response.success == false) { var arr = response.errors; jQuery.each(arr, function(index, value) { if (value.length != 0) { jQuery("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>'); } }); jQuery("#validation-errors").show(); } else { jQuery("#output").html("<img src='"+response.file+"' />"); jQuery("#output").css('display','block'); } } jQuery(document).ready(function() { var options = { beforeSubmit: showRequest, success: showResponse, dataType: 'json' }; jQuery('body').delegate('#image','change', function(){ jQuery('#kv_upload').ajaxForm(options).submit(); }); });
That’s it. and create files folder on your public/files/images/ and make the directory permission as 0777.