I have a site where I am allowing a user to select an image. I want this image to be uploaded to my database. I am using php to upload and using Ajax function to pass the image. However, it looks like the image is not really passing as an image but as a .bin when I open the image from my database. Here is my Ajax function
<script>
function AddItem(){
var name = document.forms["additemform"]["nc_name"].value;
var tag = document.forms["additemform"]["nc_tag"].value;
var description = document.forms["additemform"["nc_description"].value;
var image = document.forms["additemform"]["nc_image"].value;
var isValid = false;
$.ajax({
type: "POST",
url: "/AddNewItem.php",
data: { "Item_Name": name, "Item_Tag": tag, "Item_Description": description, "Item_Image": image },
dataType: "json",
success: function(resp){
console.log(resp);
if(resp.reply == "Success")
{
isValid = true;
form.submit();
}
else
{
isValid = false;
}
},
error: function(data, status){
console.log(data, status);
alert("error")
}
}); //end Ajax
console.log(isValid);
return isValid;
};
</script>
In my AddNewItem.php files, I am grabbing the image like this:
$itemimage = base64_encode($_POST["Item_Image"]);
after this, I simply upload to database. Uploading is working but it looks like I am uploading in wrong format. What am I doing wrong. I need to make sure it is a jpeg getting uploading but it is uploading in a .bin format.
you can use FormData example
$('#add_form').submit(function (e) {
e.preventDefault();
var name_ar = $('#form_name_ar').val();
var name_en = $('#form_name_en').val();
var token = $('#form_token').val();
var formData = new FormData($('#add_form')[0]);
formData.append('file', $('input[name=form_file]')[0].files[0]);
formData.append('name_ar', name_ar);
formData.append('name_en', name_en);
formData.append('_token', token);
$.ajax({
url: add_url,
method: 'post',
data: formData,
contentType: false,
processData: false,
success: function (data) {
toastr.success(data);
$('#users-table').DataTable().ajax.reload();
$('#form_name_ar').val('');
$('#form_name_en').val('');
$("html, body").animate({
scrollTop: 0
}, 1000);
},
error: function(data){
toastr.error(data.responseJSON)
}
})
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.