I'm using JCrop and the code provided here How should I crop the image at client side using jcrop and upload it?, which is working great except I don't know how to upload the cropped image to the server.
Here's the most relevant piece of the javascript/ajax
$("#form").submit(function(e) {
e.preventDefault();
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob(canvas.toDataURL('image/png'));
//---Add file blob to the form data
formData.append("cropped_image[]", blob);
$.ajax({
url: "sendImage.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
alert("Success");
},
error: function(data) {
alert("Error");
},
complete: function(data) {}
});
});
The canvas is added to a div 'views'.
<div id="views"></div>
And here's what php I have so far to try to upload the image
//File destination
$destination = '../Images/Uploads/';
//Get uploaded image file it's temporary name
$image_tmp_name = $_POST["formData"];
//Move temp file to final destination
move_uploaded_file($image_tmp_name, $destination);
I know I'm way off but any pointers would be great, thank you so much!
I know I'm wrong with the temp filename $image_tmp_name = $_POST["formData"];, should that be "views" instead of "formData"?
Edit to add:
$upload_dir = '../Images/uploads/';
$img = $_FILES['views'];
$img = str_replace('data:image/jpg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.jpg";
$success = file_put_contents($file, $data);
Is this any closer? I realised I was using 'image/png' when my images are jpg so I've changed the png's to jpg's. Still getting a blank jpg when I try to save it. I've scoured stackoverflow all day for an answer and haven't got any further, please can anyone give me a hint as to what to do? Thank you!
Related
Okay, so I've been on the search for an answer for weeks now.
Disclaimer
I'm new to Web development and I've learnt all by my own. Sometimes I get stuck but I've never been this stuck before.
The Problem
I want to have an Upload button on my site that automatically uploads the image to a folder and changes the background image of the same page without being redirected. This image's Path will be stored in a cookie that the user will load each time he accesses the page and the same image will be loaded as the background image. Exactly the same that Google does on its standard Tabbing page on the right bottom of the screen.
I've researched and apparently AJAX is perfect for this scenario since it enables for JQuery to mediate the php file. However I cant seem to understand how to use it in the way I need it.
This is what I have for the button, php file and the JQuery AJAX function:
The code I just showed you doesn't seem to work.
index.php
<form method="post" enctype="multipart/form-data" action="upload.php" id="file_uploader">
<div class="upload-btn-wrapper">
<button class="btn">Upload</button>
<input id="image_upload" type="file" name="file"/>
<button type="submit" value="Submit" class="btn" style="visibility:none;"></button>
</div>
</form>
.js
$(document).ready(function (e){
$("#uploadForm").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: { imageurl : $final,},
dataType: 'json',
contentType: false,
cache: false,
processData:false,
success: function(result) {
alert($final);
document.body.style.backgroundImage = $final;
},
error: function(){}
});
}));
});
.php
if(isset($_FILES['userImage'])){
$errors= array();
$file_name = $_FILES['userImage']['name'];
$file_size =$_FILES['userImage']['size'];
$file_tmp =$_FILES['userImage']['tmp_name'];
$file_type=$_FILES['userImage']['type'];
$file_ext=strtolower(end(explode('.',$file_name)));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
$final = "url(Uploads/".$file_name.")";
if(empty($errors)==true){
move_uploaded_file($file_tmp,"Uploads/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
Because I am using XAMPP to test before committing, it doesn't work yet, but not even the image is changing.
I noticed some of your ID's you're referencing in your JS file doesn't seem to match your HTML code.
// Original
$('#uploadForm').on('submit', function(e) { ... }
// Should it be?
$('#file_uploader').on('submit', function(e) { ... }
Also
// Where is $final defined and is the extra coma required?
data: { imageURL : $final,},
This is what I use to upload CSV files. It might work in your situation also.
JS
var formData = new FormData();
var fileName = $('#image_upload').val();
var file = $('#image_upload').prop('files')[0];
formData.append('file', file);
$.ajax({
url: uploadURL, // PHP file to handle uploads
dataType: 'text', // Expected return type
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function(response){
// Handle response
var path = 'path to image upload dir';
$('#bgImage').css('background-image', path + response);
}
});
PHP
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
$path = 'path to image upload dir';
$image = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $path . $_FILES['file']['name']);
setcookie("bg_image", $image, time()+3600, "/", "example.com");
echo $image;
}
Not saying this is going to perfectly fix your problem, but hopefully it'll help you get to a working solution.
So I am having some issues using jQuery to POST data to a php script. I am passing the image data from a canvas to php that will in turn save the image to the server. I am wanting this to stay as a string when sending to make it easy when the php gets it. I have tried send in json as well and no success with that. The issue is I am not getting anything in return. I have no errors in the console and php isn't leaving any errors for me either to find. I also am for the time being writing the info passed to a txt file as well to verify that data is being passed and it as well is empty. What am I doing wrong? Also I have verified the DataURL var has info in it using an alert and it contains a nice string.
var dataURL = Grabcanvas.toDataURL();
$.ajax({
url: 'upload.php',
method: 'POST',
dataType : 'text',
data: {Image:dataURL},
success : function(data) {
console.log("sucessfull sending:");
console.log(data);
},
error : function() {
console.log('failed');
}
The php code
$writeDir = "dir/text/";
$upload_dir = "dir/image/";
$img = $_REQUEST['Image'];
$myfile = fopen($writeDir."newfile.txt", "w") or die("Unable to open file!");
$txt = $img . "\n";
fwrite($myfile, $txt);
fclose($myfile);
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
file_put_contents($file, $data);
In your ajax call you have the key as Image {Image:dataURL} but in your php script your trying to access image $_REQUEST['image'], the key is case sensitive. change the one in ajax to image
you may try this
var dataURL = Grabcanvas.toDataURL();
var data = new FormData(); // added this line
data.append('Image', dataURL); // I have added this line
$.ajax({
url: 'upload.php',
method: 'POST',
dataType : 'text',
data: data, //I have changed this
success : function(data) {
console.log("sucessfull sending:");
console.log(data);
},
error : function() {
console.log('failed');
}
In PHP code change the following
$img = $_REQUEST['Image']; //you have used image, mind it it is case sensitive
This fixed it. Apparently I was explained to by a user here that toDataURL() is used for native javascript DOM but not jQuery DOM which I am using jQuery. So after code was rewritten to reflect this it now works correctly and sends without failing
`$.ajax({
url: 'upload.php',
type: 'POST',
dataType : 'text',
data: {Image: $('#name of canvas')[0].toDataURL()}, //CHANGED
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("sucessful send:");
console.log(data);
},
error: function(d) {
console.log('error');
console.log(d);
console.log(d.responseText);
}`
I am trying to save a captured image from HTML5/Canvas with a mobile. I am using PHP (symfony2).
I followed the instructions from this post (How to save a PNG image server-side, from a base64 data source) but I get a dark empty image saved instead of what I captured.
Here is my JavaScript post code:
var dataUrl = canvas.toDataURL();
$.ajax({
type: "POST",
url: "{{ path("personne_photo_capture",{"id":entity.personne.id}) }}",
data: {
imgBase64: dataUrl
}
}).done(function (msg) {
$('#msg').html(msg);
}).fail(function (xhr, textStatus, errorThrown) {
$('#msg').html(xhr.responseText);
});
And the PHP saving code :
$rawData = $_POST['imgBase64'];
if (isset($rawData)) {
$filteredData = explode('base64,', $rawData);
$data = base64_decode($filteredData[1]);
$filename = "profil.png";
file_put_contents('picts/small/' . $filename, $data);
}
First of all, make sure to specify the datatype on the cliente side as
dataType: 'text',
On the server side replace your first two statements with :
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
For further pointers take a loop at previously asked question
How to save a PNG image server-side, from a base64 data string
I have a file type and the button named "upload Image", where I select the file and upload the image. on clicking the upload image button image should be saved in the uploads folder.
On running in the localhost it works fine but fails to upload in the server.
This is my code:
$(document).ready(function() {
$('#upload').on('click', function() {
var file_data = $('#fileToUpload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "http://mpp.ABCDEF.co.in/API/sendingInterface.php?fn= uploadImage", // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
$('#response').val(data);
},
error: function() {
alert('Error');
}
});
});
});
Function of sendingInterface.php:
if($_GET['fn'] =="uploadImage")
{
$target_dir = $obj1->images_folder();
$target_file = $target_dir . basename($_FILES['file']['name']);
header ('Content-type: application/json');
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
http_response_code(200);
$encoded = json_encode("{ success }");
exit($encoded);
}
else {
http_response_code(200);
$encoded = json_encode("{ failure }");
exit($encoded);
}
}
Where $obj1->images_folder() is having the folder name in database as ../../MPP/images/uploads/
On running in server I am getting the output as a alert box with message "Error". How can I run it in server?
Try to manually set the full path to the upload folder - for an example:
$target_dir="http://mpp.ABCDEF.co.in/API/MPP/images/uploads/"
But you can't be sure with this relative path where the folder is. You have to find it by ftp-client or file manager - I don't know what is your hosting tools.
At all it is not good idea to use relative paths, because probably the config path and your base points are different.
I am successfully saving file in database as blob from ajax request to php file.
My ajax is like this
var file = $('#fileuploader')[0].files[0];
var formData = new FormData();
formData.append('file', file);
}
$.ajax({
url: '../include/Addnewstudent.php',
type: 'POST',
dataType: "json",
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(data) {
console.log(data);
// window.location.reload(true);
}, error: function(data) {
alert("Error!"); // Optional
//window.location.reload(true);
}
});
in my PHP i have
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
where i check the file like
if ($fileError == UPLOAD_ERR_OK) {}
My question is very simple how can i make it in a way that when the i dont want to put file it is ok.Currently when i dont put anything in the input(type file) i always get error in the $fileName = $_FILES['file']['name']; saying file is undefined so i cant make an if condition as if($fileSize = $_FILES['file']['size'] > 0) or/and i cant leave the input(type file) empty because i will certainly get the undefined index for file. How can i be able to leave the input(type file) empty and dont get the error undefined index : file. Any idea is appreciated.
GOAL
The flexibility to save or not save file in database
You have to check if $_FILES['file'] exist.
if (isset($_FILES['file'])) {
// process file
}
Based on Keo's answer i played with it and i came up with this
if (!empty($_FILES)) {
and now i can save and not save based on my requirements. I achievement my goal to upload and not to upload depending on what i need