1
Currently I did a mini file upload project using the Asynchronous File Uploader (Ajax) and it worked. I went to try to upload images using ajax and my request is returning null, so I can not manipulate the database.
I already looked for some solutions in the forum and none solved, I saw that many were the enctype problem of the form, but I believe that mine is not.
Route:
Route::get('/', 'PostControlador@index');
Route::get('/arquivos-json', 'PostControlador@index');
Route::post('/', 'PostControlador@store');
View:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="arquivo" id="arquivo">
<button type="button" class="btn btn-primary btn-save-post">Enviar</button>
</form>
Javascript:
$('.btn-save-post').on('click', function(){
let formData = new FormData();
formData.append('arquivo', $('#arquivo').val());
$.ajax({
url: '{{ url('/') }}',
method: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
data: formData,
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
Controller:
public function store(Request $request)
{
dd ( $request->all() );
// result: ["arquivo" => "C:\fakepath\2028_2229862022_a2e8c5716f_320_240_nofilter.jpg"]
dd ( $_FILES );
// result: []
dd ( $request->file('arquivo') );
// result: null
dd ( $request->arquivo );
// result: "C:\fakepath\65535_48730933186_d4b4dd1979_320_240_nofilter.jpg"
}
As you might have seen in this code, the $request->all() and $request->file Normally return the file, the global $_FILES and the $request->file('file') return null.
Exits the ajax and goes straight to the slider and picks up $request->file('file'); or uses js fileReader
– Lucas Antonio
@Lucasantonio thanks for commenting, but in this case it would be asynchronous, like ajax without having to refresh the page?
– Igor AC
With $request->file it will not redirect to another screen and come back, with ajax tries to use fileReader which is the js library to work with files.
– Lucas Antonio