admin管理员组文章数量:1296255
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
HTML (the button to open the modal with Sweet Alert 2):
<button class="bx--btn bx--btn--primary" type="button" id="swal_upload">Apri</button>
JavaScript:
$('#swal_upload').click(function(){
var api = 'api/UploadFile.php';
swal({
title: "Carica immagine",
html: '<input id="fileupload" type="file" name="userfile">'
}).then(function() {
var formData = new FormData();
formData.append('userfile', $('#fileupload').val().replace(/.*(\/|\\)/, ''));
console.log(formData);
$.ajax({
type: 'POST',
url: api,
data: formData,
dataType: 'json',
processData: false,
contentType: false,
headers: {"Content-Type":"form-data"},
async: true,
success: function(result){
console.log("OK client side");
console.log(result.Response);
}
});
})
});
php (api/UploadFile.php):
$entered = "PHP started";
$tmpFilePath = $_FILES['userfile']['tmp_name'];
$uploaddir = 'public/';
if ($tmpFilePath != ""){
$newFilePath = $uploaddir . basename($_FILES['userfile']['name']);
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$uploaded = "Upload OK server side";
} else {
$uploaded = "Upload failed server side";
}
}
// Prepare response, close connection and send response to front-end
$array['Response'] = array(
'entered' => $entered,
'tmp_path' => $tmpFilePath,
'new_path' => $newFilePath,
'file_name' => $_FILES['file']['name'],
'uploaded' => $uploaded
);
echo json_encode($array);
The output I have in the console is:
FormData {}proto: FormData OK client side {entered: "PHP started", tmp_path: null, new_path: null, file_name: null, uploaded: null} entered:"PHP started" file_name:null new_path:null tmp_path:null uploaded:null proto:Object
As you can see the php starts, but no file is passed to the server.
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
HTML (the button to open the modal with Sweet Alert 2):
<button class="bx--btn bx--btn--primary" type="button" id="swal_upload">Apri</button>
JavaScript:
$('#swal_upload').click(function(){
var api = 'api/UploadFile.php';
swal({
title: "Carica immagine",
html: '<input id="fileupload" type="file" name="userfile">'
}).then(function() {
var formData = new FormData();
formData.append('userfile', $('#fileupload').val().replace(/.*(\/|\\)/, ''));
console.log(formData);
$.ajax({
type: 'POST',
url: api,
data: formData,
dataType: 'json',
processData: false,
contentType: false,
headers: {"Content-Type":"form-data"},
async: true,
success: function(result){
console.log("OK client side");
console.log(result.Response);
}
});
})
});
php (api/UploadFile.php):
$entered = "PHP started";
$tmpFilePath = $_FILES['userfile']['tmp_name'];
$uploaddir = 'public/';
if ($tmpFilePath != ""){
$newFilePath = $uploaddir . basename($_FILES['userfile']['name']);
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$uploaded = "Upload OK server side";
} else {
$uploaded = "Upload failed server side";
}
}
// Prepare response, close connection and send response to front-end
$array['Response'] = array(
'entered' => $entered,
'tmp_path' => $tmpFilePath,
'new_path' => $newFilePath,
'file_name' => $_FILES['file']['name'],
'uploaded' => $uploaded
);
echo json_encode($array);
The output I have in the console is:
FormData {}proto: FormData OK client side {entered: "PHP started", tmp_path: null, new_path: null, file_name: null, uploaded: null} entered:"PHP started" file_name:null new_path:null tmp_path:null uploaded:null proto:Object
As you can see the php starts, but no file is passed to the server.
Share Improve this question edited Jan 17, 2018 at 14:38 Luca Crippa asked Jan 17, 2018 at 14:13 Luca CrippaLuca Crippa 171 gold badge2 silver badges8 bronze badges 3- 1 It is difficult to offer solutions when the problem statement is simply, "it doesn't work". Please edit your question to give a more plete description of what you expected to happen and how that differs from the actual results. See How to Ask for hints on what makes a good explanation. – Toby Speight Commented Jan 17, 2018 at 14:15
- you can not use ajax to upload data this way. especially with "Content-Type":"form-data" – Paun Narcis Iulian Commented Jan 17, 2018 at 14:23
- @PaunNarcisIulian do you have a solution? – Luca Crippa Commented Jan 17, 2018 at 15:02
1 Answer
Reset to default 8I 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);
}
本文标签: javascriptSweet Alert 2 jQuery file upload with phpStack Overflow
版权声明:本文标题:javascript - Sweet Alert 2 jQuery file upload with php - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741634311a2389553.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论