Skip to content

Instantly share code, notes, and snippets.

@umihico
Last active July 12, 2019 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umihico/656bae3df518a8b4bb73d8f89f31c0cb to your computer and use it in GitHub Desktop.
Save umihico/656bae3df518a8b4bb73d8f89f31c0cb to your computer and use it in GitHub Desktop.
Get CSV as array from input form with ajax in Laravel 5.8.14
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/parse_csv',function (Request $request){
$file_name = $request->file('formdata_key')->store('');
$file_path=\Illuminate\Support\Facades\Storage::disk('local')->path($file_name);
\Illuminate\Support\Facades\Log::info($file_name);
$csv = array();
if (($file = fopen($file_path, 'r')) !== false){
\Illuminate\Support\Facades\Log::info('a');
while (($line = fgetcsv($file, 1000)) !== false){
$csv[] = $line;
}
fclose($file);
}
\Illuminate\Support\Facades\Log::info($csv);
});
<html><head>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head><body>
<input id="inputid" type="file"/>
<button id="upload">Upload</button>
<script>
$('#upload').on('click', function() {
var file_data = $('#inputid').prop('files')[0];
var form_data = new FormData();
form_data.append('formdata_key', file_data);
$.ajax({
url: '/api/parse_csv',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response);
}
});
});
</script>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment