Last active
July 12, 2019 08:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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