File Upload in Laravel 5 using Ajax With Form Data
Today, I am going to show you How to upload excel or image file using jquery Ajax in Laravel application. In this tutorial we are going to learn step by step example code of upload excel file using jquery Ajax form.
<meta name="_token" content="{{ csrf_token() }}" />
HTML Code
<form id="uploadfile" class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<div class="block">
<div class="panel-body">
<div class="form-group">
<label class="col-md-3 control-label">Upload File<span class="required">*</span></label>
<div class="col-md-9">
<input required="" type="file" name="result_file" id="result_file" />
</div>
</div>
<div class="btn-group pull-right">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</div>
</div>
</form>
Ajax call with validation excel file
$("#uploadfile").on("submit", function(e) { e.preventDefault(); var extension = $('#result_file').val().split('.').pop().toLowerCase(); if ($.inArray(extension, ['csv', 'xls', 'xlsx']) == -1) { $('#errormessage').html('Please Select Valid File... '); } else { var file_data = $('#result_file').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); $.ajaxSetup({ headers: { 'X-CSRF-Token': $('meta[name=_token]').attr('content') } }); $.ajax({ url: "{{url('postFile')}}", // point to server-side PHP script data: form_data, type: 'POST', contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData: false, success: function(data) { } }); } });
Ajax call in Routes
Route::post('postFile', [
'as' => 'postFile',
'uses' => 'UploadFileController@postFile'
]);
Routes Call in Controller and with excel file upload in specific folder.
$extension = $request->file('file');
$extension = $request->file('file')->getClientOriginalExtension(); // getting excel extension
$dir = 'assets/files/';
$filename = uniqid().'_'.time().'_'.date('Ymd').'.'.$extension;
$request->file('file')->move($dir, $filename);
Leave a Reply