Hi,
I want to upload an image file using JQuery AJAX and send it to php code for further processing including image cropping. I tried this code for Js:
<script type="text/javascript">
$(document).ready(function() {
$('#uploadstatus1').hide();
$('#uploadstatus2').hide();
$('#btnupload').click(function() {
var file = $('#formFile')[0].files[0];
var filename = file.name;
var filedata = $('#formFile').prop('files')[0];
var formdata = new FormData();
formdata.append("file", filedata);
formdata.append("filename", filename);
$.ajax({
url: "../app/model/saveimage.php",
type: "POST",
dataType: 'script',
cache: false,
processData: false,
data: formdata,
success: function(data2) {
if (data2 == 1) {
location.reload();
} else {
alert(data2);
$('#uploadstatus1').show();
}
}
});
});
});
</script>
Uploading modal:
<div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Upload image</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="" method="POST" enctype="multipart/form-data">
<p>Upload file:</p>
<div class="mb-3">
<label for="formFile" class="form-label">Only Jpeg files are supported.</label>
<input class="form-control" type="file" id="formFile" name="formFile" required>
</div>
</form>
<div class="alert alert-danger" id="uploadstatus1" role="alert">
Upload failed!
</div>
<div class="alert alert-success" id="uploadstatus2" role="alert">
File uploaded successfully!
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" name="btnupload" id="btnupload">Upload</button>
</div>
</div>
</div>
</div>
saveimage.php:
if (isset($_POST['file'])) {
try {
//For uploading original image
$crop = new Crop();
$crop->img_name = $_FILES['file']['name'];
$crop->tmp_img_name = $_FILES['file']['tmp_name'];
$crop->folder = "../public/assets/uploadIMG/";
//For finding file extension
$crop->ext = pathinfo($crop->img_name, PATHINFO_EXTENSION);
//Renaming the uploaded file
$crop->new_name = $this->RandomStringGenerator() . "." . $crop->ext;
$this->new_name = $crop->new_name;
//Moving to the desired path
move_uploaded_file($crop->tmp_img_name, $crop->folder . $crop->new_name);
$this->RegisterIntoDatabase();
//For cropping image and creating thumbnail
$crop->RunCrop();
unset($_POST);
echo '1';
} catch (\Throwable $th) {
echo '2';
}
}else{
echo '2';
}
The problem is that if (isset($_POST[‘file’])) returns false.
How can I solve this problem?