My page has a file input. When the user uploads a photo, they then crop it and the result is stored in an img element (using FileReader).
How can I submit this image through jQuery ajax?
EDIT
I got something working. There are 2 problems though. First, the image file size is really big (almost 1MB for a 600x600 picture).
Second, I am not sure how to verify in PHP that the file uploaded is an image.
$pic = $_POST['pic'];
$pic = str_replace('data:image/png;base64,', '', $pic);
$pic = str_replace(' ', '+', $pic);
$pic = base64_decode($pic);
$path = "c:/wwwroot/images/img.jpg";
file_put_contents($path,$pic);
Using ajax you could read file bytes using FileReader Convert it to base64 and then send it to server. This is how It goes:
var sendingcanvas = document.getElementById('sendingcanvas');
var dataURL = sendingcanvas.toDataURL("image/*");
var imagedatatosend = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
var formdata = new FormData();
formdata = {
'image': imagedatatosend
};
$.ajax({
url: 'serverside',
type: 'POST',
data: formdata,
encode: false,
cache:false,
success: function(data){}
});
Easy and Recommended Way:
function upload(file, servlet){
var xhr=new XMLHttpRequest(), sres=null;
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
sres=xhr.responseText;
}
}
xhr.open('post',servlet,false);
xhr.send(file);
return sres;
}
Call the function Inputing image location and serverside link And you are good to go :)
you question need more description but as for normal image image upload code is here:
$(document).on('submit', 'form', function (event) {
event.preventDefault();
var form_data = new FormData();
$($(this).prop('elements')).each(function () {
if (this.type == 'file')
form_data.append(this.name, this.files[0]);//here you can upload multiple image by iterating through files[]
else
form_data.append(this.name, $(this).val());// for text fields
});
$.ajax({
type: "POST",
cache: false,
contentType: false,
processData: false,
url: $(this).attr('action'),
data: form_data,
beforeSend: function () {
},
success: function (data) {
},
error: function (data) {
});
}
});
});
if (this.type == 'file')
form_data.append(this.name, this.files[0]);
this will add data from input type file data to form_data and then it will be send by ajax
Related
I have ajax code which can post name and I have another ajax which can post image I need to combine those two functions in order to have one function which can post both name and image
Below codes used to post image
<script>
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
},
});
}else{
alert("Please select a file.");
}
});
});
</script>
And below codes used to post name
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
$.ajax({
type:"post",
url:"upload.php",
data:
{
'name' :name
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
How can I combine above codes in order to use only one url "upload.php", this means upload.php will insert name in database and save image in folder while click save button, that's why I need to combine the codes
Please anyone can help me
You literally combine them.
You can use your first function and do the following:
var fd = new FormData();
var files = $('#file')[0].files;
fd.append('name', $("#name").val();
that is it. And on the other side (backend) you just ask for this name:
$name = $_POST['name'];
In ajax I got it working but in javascript.
Ajax
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
AJAX request
$.ajax({
url: 'https://url/ajax.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully');
}
});
In JavaScript
var request = makeHttpObject();
request.open("POST", "https://url/ajax.php", true);
request.send(base64URL);
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
console.debug(request.responseText);
} else {
console.debug(request.responseText);
}
};
JS uploads to server image with 0 kb.
Should it append in image file base64 ? That's why it is 0? Tried several things searching but still not working.
I have a small symfony 4 application with a cropper using CroppieJS.
When i crop and hit the save button, croppie sends me a base64 image :
$( "#cropSave" ).click(function() {
basic.croppie('result','canvas'
).then(function (result) {}
how to send this result to my controller and persist the image with VichUploader and Doctrine ?
Here is my controller :
public function updateProfilePicture(Request $request): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
$user->setImageFile($request->files->get('image'));
$entityManager->flush();
return new Response("ok");
}
I tried a lot of things but I must lack experience because it don't work :
var form = document.getElementById("myAwesomeForm");
var ImageURL = result;
// Split the base64 string in data and contentType
var block = ImageURL.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1];
// get the real base64 content of the file
var realData = block[1].split(",")[1];
// Convert it to a blob to upload
var blob = b64toBlob(realData, contentType);
// Create a FormData and append the file with "image" as parameter name
var formDataToUpload = new FormData(form);
formDataToUpload.append("image", blob);
or
function urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
);
}
here is one of my ajax request :
$.ajax({
type : "POST",
data: formDataToUpload,
url : $('#updateProfilePictureLink').val(),
contentType:false,
processData:false,
cache:false,
dataType:"json",
success : function(response) {
$('#profilePicture').attr('src', result);
alert(response);
},
error : function (response) {
alert("error !");
}
});
I was thinking maybe "Simulate" a file upload in JS from the base64 using VichUploader formType input field, but I want to know if there are simpler ways.
Thanks
I managed to work around it thanks to Ronnie Hint.
You have to :
use JS FormData
put the blob inside
retrieve it in Symfony controller as an image
save it as is
But you have to implement serializable on your image's entity (serialize and unserialize all fields, unless it will break your other features).
Here is the working code sample :
// JS
$( "#cropSave" ).click(function() {
alert("click !");
basic.croppie('result','blob'
).then(function (result) {
var fd = new FormData();
//Third parameter is the blob name
fd.append('data',
result,$('#userId').val()+"."+result.type.split("/")[1]);
$.ajax({
type: 'POST',
url : $('#updateProfilePictureLink').val(),
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// your things
});
// PHP
// Controller
try {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
$user->setImageFile($request->files->get('data'));
$entityManager->flush();
}
catch (exception $e) {
}
// Entity
class User implements UserInterface, \Serializable
{
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->profilePicture,
$this->email,
$this->password
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->profilePicture,
$this->email,
$this->password
) = unserialize($serialized);
}
I made this code to make image upload function but the variable is not getting posted by ajax please help me !!
Jquery()
<script type="text/JavaScript">
$(document).ready(function() {
$("#btn").click(function() {
$.get("i.png", function(response) {
var img = response;
});
$.ajax({
type: "POST",
url: 'lol.php',
data: {r: img},
success: function(data){
$("#ol").html(data)
}
});
return false;
});
});
</script>
PHP Code
<?php
$conn = mysqli_connect("localhost","root","","image");
$r = $_POST['r'];
echo $r;
?>
If you only want to make an image upload (and not exactly match "binary upload")
I suggest you to use the proper functional and native input type file.
In a html form, put an :
<input type="file" id="upload">
<img src="blank.png" title="upload-preview">
and in you javascript:
this will load the preview thumbnail selected
fileInput.addEventListener("change", function(event)
{
var file = $("#upload")[0].files[0];
$(".upload-preview").attr('src', window.URL.createObjectURL(file));
});
and when you click the button, that will send the image
with a "multipart/form-data" Content-Type
$("#btn").on("click", function()
{
var inputs = new FormData();
inputs.append("upload", $("#upload")[0].files[0]);
$.ajax
({
url:"your.php",
type:"POST",
data: inputs,
cache: false, // don't cache the image
processData: false, // Don't process the files
contentType: false,
success: function(response)
{
// next instructions
}
});
});
I have the following ajax function:
reader.onload = function(event){
var fd = new FormData();
var Name = encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
console.log("name = " + Name);
fd.append('fname', Name);
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false,
success: function(data){
//console.log(data);
$.ajax({
type: 'POST',
url: 'readFile.php',
data: {"fileName":fileName},
success: function(data){
console.log(data);
}
});
}
});
};
first question: I want to retrieve the data from the second success function to use it later in the code.how could that happen?
second question: the data is an audio file.Is there is a special way to get audio data, or we can get it the same way as any data?In my php server side of the second ajax, I'm reading an audio file and want to use its data.I did simple file open and get contents.does that work for audio files?
server-side code:
<?php
$fileName=$_POST["fileName"];
$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;
This is a bad practice in general, but what you could do is specify a global variable at the start, and then assign data to that variable inside the success. The issue with this is that you can't be certain that the ajax has completed and your variable has been set, before you need to use it.
var mySuccessVar = null;
...
success: function(data) {
mySuccessVar = data;
}
... // later in the code:
if (mySuccessVar != null) {
yourFunction(mySuccessVar);
}