I\'m trying to create a file uploader inside a Sweet Alert 2 modal with jQuery and php. Here\'s my code, but it isn\'t working: how can I get this working?
Thank you
I used a solution based on the input file type from Sweetalert 2 and the FileReader/FormData objects from the view side.
When you use an input file type of Sweetalert, an input element with the swal2-file
css class will be created:
Then you can use the Sweetalert event onBeforeOpen
to read the file data through the FileReader object. Finally you can send the file using ajax request with the FormData object.
This would be the js source:
$('#swal_upload').click(function() {
Swal({
title: 'Select a file',
showCancelButton: true,
confirmButtonText: 'Upload',
input: 'file',
onBeforeOpen: () => {
$(".swal2-file").change(function () {
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
});
}
}).then((file) => {
if (file.value) {
var formData = new FormData();
var file = $('.swal2-file')[0].files[0];
formData.append("fileToUpload", file);
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
method: 'post',
url: '/file/upload',
data: formData,
processData: false,
contentType: false,
success: function (resp) {
Swal('Uploaded', 'Your file have been uploaded', 'success');
},
error: function() {
Swal({ type: 'error', title: 'Oops...', text: 'Something went wrong!' })
}
})
}
})
})
From the server side, using Laravel Php framework, you can get the file through a function like this:
public function uploadFile(Request $request)
{
if ($request->hasFile('fileToUpload')) {
$file_name = $request->file('fileToUpload')->getClientOriginalName();
$earn_proof = $request->file('fileToUpload')->storeAs("public/files/", $file_name);
}
return response()->json(['result' => true], 200);
}