Summernote image upload not working in codeigniter - javascript

I have integrated summernote in my website (built with Codeigniter) and for texts it is working fine. But for image upload, there arises the following problem.
Summernote reads the image as base64. Now this works perfectly fine for small images, but once images are large, the image finally does not render due to the huge string created by the base64 in the database.
So I am trying to save the image in my server and then use the link of that image.
Following are the codes:
Script for summernote:
<script type="text/javascript">
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
onImageUpload: function(files) {
sendFile(files[0]);
}
});
function sendFile(file) {
data = new FormData();
data.append("files", file);
upload_url = "<?php echo base_url(); ?>" + "general/upload_image";
$.ajax({
data: data,
type: "POST",
url: upload_url,
cache: false,
contentType: false,
processData: false,
success: function(url) {
$(this).summernote("insertImage", url);
}
});
}
});
the php upload_image function:
public function upload_image()
{
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = 'http://sitename.com/dist/img/blogimg/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'http://sitename.com/dist/img/blogimg/' . $filename;//change this URL
}
else
{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
}
now, when I click on insert image in summernote or drag and drop an image multiple instances of the following error is shown in the console:
>Uncaught TypeError: Cannot read property 'nodeType' of undefined
This is what I want to achieve,
N.B. This editor is for a blog.
1. User clicks on insert image and uploads an image from his computer.
2. the image is shown in the editor (but not uploaded to server at this step).
3. When user clicks on submit button, then the image should be saved as an image file in a predefined folder.
4. When the page renders the it should have
<img src="mysite.com/path_to_image">
now it is something like
<img src="data:image/jpeg;base64,/9j/4AAQSkZJR....">)
Please note, I tried using onImageUpload within callbacks but the result was nothing was actually happening, neither the image was geting uploaded to the editor nor to the folder in the server.
Where am I going wrong....?? Please help me fix this...

if your summernote version after 0.7
following this
$('#summernote').summernote({
height: 400,
callbacks: {
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0]);
}
}});

Okay, although I could not find a solution to my problem, I have implemented an alternation solution and it works perfectly, although pt. 3 is not catered to and the image is uploaded to the server in an earlier step. That too can be catered with some js scripts...Will do that later... What I did is I targeted the summernote ids and classes and added my codes in place of theirs...
I removed their upload image field by this code:
<style>
/*to disable the upload image from computer uncomment this css code.*/
.note-group-select-from-files {
display: none;
}
</style>
Next I inserted my HTML below their insert link field this way:
document.getElementsByClassName('note-group-image-url')[0].insertAdjacentHTML('afterend','<p class="sober"><p>Click here to upoad image</p></i></p>');
Next I handled the image upload through a modal and wrote a custom js script that copied the image url to the field of .note-image-url
Also I had to customise the javascript of the insert image button of summernote with js so that users can directly click on insert image.

You can add this to your store/ update controller.
It will detect images in your editor, convert and save it in your server.
$body = $data['content'];
$doc = new DomDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($body);
$images = $doc->getelementsbytagname('img');
define('UPLOAD_DIR', 'assets/images/announcement_img/');
foreach($images as $k => $img){
$datas = $img->getattribute('src');
if (strpos($datas, 'data:image')!==false){
list($type, $datas) = explode(';', $datas);
list($media, $format) = explode('/', $type);
list(, $datas) = explode(',', $datas);
$datas = str_replace(' ', '+', $datas);
$datas = base64_decode($datas);
$file= UPLOAD_DIR . time().$k.'.'.$format;
$success = file_put_contents($file, $datas);
print $success ? $file : '<br><br>Unable to save the file.<br><br>';
$img->removeattribute('src');
$img->setattribute('src',base_url().$file);
}
}
$body = $doc->savehtml();
$data['content']=$body;

Related

How doo I resolve getting a 500 error when calling $.post

My website has a drawing tool. This drawing tool help met create an image (.png) from the drawing. Has been working for years now, but recently changed the wordpress theme.
Now I can't figure out what's going wrong.
I have the following code which is doing a POST request to a file in my theme folder
var templateUrl = 'https://example.nl/wp-content/themes/generatepress';
var strDataURI = canvas.toDataURL("image/jpg",'',1.0);
var jsnDataJSON = encodeURIComponent(JSON.stringify(canvas));
$('input[name=json]').val(jsnDataJSON);
strDataURI = strDataURI.substr(22, strDataURI.length);
var ajax_urll= templateUrl+"/ajax.php";
$.post(ajax_urll,
{
str: strDataURI
},
function(data){
var obj=jQuery.parseJSON(data);
if(obj.status!="ERROR"){
jQuery("#drawing").html(obj.image);
jQuery("#drawingsaveresult").html("Drawing has been successfully saved");
jQuery("#drawingsaveresult").fadeOut(10000);
jQuery("input[name='drawing']").val(obj.imagename);
}else{
jQuery("#drawingsaveresult").html("Else error in saving drawing");
jQuery("#drawingsaveresult").fadeOut(10000);
}
});
So this code is calling ajax.php file (file in theme folder) which does the following
<?php
session_start();
// require_once( $_SERVER['DOCUMENT_ROOT'] . '/example.nl/wp-load.php' ); localhost
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
global $wpdb;
$data = base64_decode($_POST["str"]);
$urlUploadImages = "oefeningen/";
$nameImage = rand()."drawing.png";
$img = imagecreatefromstring($data);
imageAlphaBlending($img, true);
imageSaveAlpha($img, true);
$response=array();
if($img) {
imagepng($img, $urlUploadImages.$nameImage, 0);
imagedestroy($img);
get_stylesheet_directory_uri();
$response['image']="<img src='".get_stylesheet_directory_uri()."/oefeningen/".$nameImage."' width=100 height=150>";
$response['imagename']=$nameImage;
$response['status']="success";
}
else {
$response['status']="ERROR";
}
echo json_encode($response);
But for some reason it's not working anymore. In the console it's giving the following error back
POST https://example.nl/wp-content/themes/generatepress/ajax.php 500
I can't find a resolution. Can someone assist me with this?

Uploading capture image and store it in a folder changing it's filename to be unique using the userID

I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.

Uploading BLOB url to PHP server via ajax - Cordova

I am building a hybrid mobile app with cordova and is using the cordova camera plugin. I was able to get the blob:url for the image but hits a dead-end with uploading it to my back-end php server.
Background information:
I have two buttons that I have created to test the cordova camera api.
1 - Take Photo Btn -> Generates a blob url
2 - Upload Photo -> Suppose to upload the image captured based on the photo take to my server via ajax.
Based on my console, I am getting index:file not found and it generates a 0KB image file on my server. I am fairly new to ajax and blob so would appreciate any assistance rendered.
//JS CODE
uploadimgtoserver : function () {
//x is the blobimage url blob:http://localhost:8000/cb420014-a0b9-481a-b3ea-
6657f7e7c98e
var x = localStorage.getItem('data');
$.ajax({
url: 'URL',
type: 'POST',
data: {'file':x},
success: function (data) {
console.log(data);
},
});
}
};
//php code
$data = $_POST['file'];
$data = str_replace('data:image/jpeg;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = uniqid() . '.jpg';
$success = file_put_contents($file, $data);

trigger click automatically using jquery to export all graphs as image

I have multiple graphs in a single html page.I am trying to export all the graphs after the complete loading of all the graphs on that page.
I have the script to trigger the click event, but it's not working as I want it.
I want to trigger click button so that it pushes the graph image in an array as base64 encoded then send the data to a php file and save it as an image.
Two images are being created but only one image is proper and the other image is corrupt.
here is my code to graph generation:
https://jsfiddle.net/a1so23dh/2/
here is my php file code:
<?php
$data = urldecode($_POST['imageData']);
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$filename = "images/image".rand(1000,10000).".jpg";
file_put_contents($filename, $data);
?>
Any other approach may also work.
A better approach would be to just use the API methods in AmCharts' events and the AmCharts export plugin API instead of using fake clicks, similar to the first example in this tutorial. It uses the rendered event, but animationFinished works as well:
"listeners": [{
"event": "animationFinished",
"method": function(e) {
//wait for fabric
var interval = setInterval(function() {
if (window.fabric) {
clearTimeout(interval);
e.chart.export.capture({}, function() {
this.toJPG({}, function(data) {
//post base64 string in data to your endpoint directly
});
});
}
});
}
]
Updated fiddle - note that for debugging purposes I added the exported image to the bottom of the screen to validate that this works.
Your sendAllData() is not called. so I propose some changes, well it's not a full solution but help you.
$('*').click(function(e){
sendAllData();
});
function sendAllData(){
console.log(dataArray);
var arsize = dataArray.length;
console.log("here");
//execute this function and use the dataArray here
//send data to php file
if(arsize != 0){
for(i=0;i<=dataArray.length;i++){
jQuery.post( "a.php", {imageData: encodeURIComponent( dataArray[i] )})
.done(function( data ) {
if(data != 1){
console.log( "Data Loaded: " + data );
}else{
console.log("error");
}
});
}
}
}
In PHP use below code.
<?php
$data = urldecode($_POST['imageData']);
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
//$filename = "images/image".rand(1000,10000).".jpg";
//file_put_contents($filename, $data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/jpeg');
imagejpeg($im, "uploads/png3.jpeg");
imagedestroy($im);
}else{
echo '1';
}
?>
I am able to save the image of first graph i.e bar chart but in the pie chart, I am getting the error.please try this.

when saving canvas image server-side, from a base64 data string,it produce blank image

I have problem with saving canvas image in PHP. I get a blank .png file. I search a lot about this problem but cant find anything useful about this. Why does it save a blank image instead of rendering real image?
JavaScript code:
html2canvas([document.getElementById('dadycool')], {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var image = new Image();
image.src = data;
document.getElementById('imagec').appendChild(image);
console.log(data);
$.ajax({
type: "POST",
url: "up.php",
data: {
imgBase64: data
}
}).done(function(o) {
console.log('saved');
});
}
PHP code:
<?php
// requires php5
define('localhost/samp/sample2/uploads', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = localhost/samp/sample2/uploads . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I suspect you haven't configured your development box to display PHP error messages. You are defining a constant that is not a valid identifier:
define('localhost/samp/sample2/uploads', 'images/');
That means that you cannot use it directly:
$file = localhost/samp/sample2/uploads . uniqid() . '.png';
... should be triggering:
Notice: Use of undefined constant localhost - assumed 'localhost'
Notice: Use of undefined constant samp - assumed 'samp'
Warning: Division by zero
Notice: Use of undefined constant sample2
Warning: Division by zero
Notice: Use of undefined constant uploads - assumed 'uploads'
Warning: Division by zero
... and file will only contain the base file name (e.g. 53676a01cdb59.png) but not path component. You need to use this syntax:
$file = constant('localhost/samp/sample2/uploads') . uniqid() . '.png';
... or, even better, give the constant a sensible name:
define('DIR_UPLOADS', 'images/');
I was having this same issue - it looked like the base64 data was being sent correctly but always failed to generate the image server side. The solution I found was to use the 'FormData' object and a very simple xhr request to post to the server.
var url='/path/to/save.php';
var data=oCanvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
var fd=new FormData();
fd.append('imgdata',data);
var request = new XMLHttpRequest();
request.open('POST', url);
request.send(fd);
I'm 99% sure the problem was caused by the incorrect Content-Type header being sent by the xhr request. Using a basic xhr request combined with FormData forced the xhr request to be sent with the multipart/formdata content type with correctly defined content boundaries.

Categories