image are not being displayed in ckeditor - php

I'm implementing image upload using CKEditor in laravel but images are uploaded but they're not displayed. I need help, please.
these are my code
public function upload(Request $request){
if($request->hasFile('upload')){
$originalName=$request->file('upload')->getClientOriginalName();
$fileName=pathinfo($originalName,PATHINFO_FILENAME);
$extension=$request->file('upload')->getClientOriginalExtension();
$fileName=$fileName.'_'.time().'.'.$extension;
$request->file('upload')->move(public_path('images'),$fileName);
$CKEditorFuncNum=$request->input('CKEditorFuncNum');
$url=asset('public/images/'.$fileName);
$msg='Image uploaded successfully';
$response="<script >window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum,'$url','$msg')</script>";
#header('content-type:text/html','charset-utf-8');
echo $response;
}
}
and output is this

put these script to your html file
<script src="https://cdn.ckeditor.com/4.14.1/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace( 'summary-ckeditor', {
filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}",
filebrowserUploadMethod: 'form'
});
and put these code in your image controller
if($request->hasFile('upload')) {
$originName = $request->file('upload')->getClientOriginalName();
$fileName = pathinfo($originName, PATHINFO_FILENAME);
$extension = $request->file('upload')->getClientOriginalExtension();
$fileName = $fileName.'_'.time().'.'.$extension;
$request->file('upload')->move(public_path('images'), $fileName);
$CKEditorFuncNum = $request->input('CKEditorFuncNum');
$url = asset('images/'.$fileName);
$msg = 'Image uploaded successfully';
$response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
#header('Content-type: text/html; charset=utf-8');
echo $response;
}

Related

PHP - How can I remove image in Froala text editor v4?

I am trying to remove image in froala text editor, I can upload image, but i can't delete image.
Here is what I am trying to achieve:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href='https://cdn.jsdelivr.net/npm/froala-editor#latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
<script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor#latest/js/froala_editor.pkgd.min.js'></script>
</head>
<body>
<div class="sample">
<h2>File upload example.</h2>
<form>
<textarea id="edit" name="content"></textarea>
</form>
</div>
<script>
new FroalaEditor('#edit', {
imageUploadURL: 'upload_image.php',
fileUploadParams: {
id: 'my_editor'
}
})
var editor = new FroalaEditor('#edit');
editor.opts.events['image.removed'] = function (e, editor, $img) {
$.ajax({
// Request method.
method: 'POST',
// Request URL.
url: 'delete_image.php',
// Request params.
data: {
src: $img.attr('src')
}
})
.done (function (data) {
console.log ('Image was deleted');
})
.fail (function (err) {
console.log ('Image delete problem: ' + JSON.stringify(err));
})
}
</script>
</body>
</html>
upload_image.php :
<?php
try {
// File Route.
$fileRoute = "/uploads/";
$fieldname = "file";
// Get filename.
$filename = explode(".", $_FILES[$fieldname]["name"]);
// Validate uploaded files.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
// Get temp file name.
$tmpName = $_FILES[$fieldname]["tmp_name"];
// Get mime type.
$mimeType = finfo_file($finfo, $tmpName);
// Get extension. You must include fileinfo PHP extension.
$extension = end($filename);
// Allowed extensions.
$allowedExts = array("gif", "jpeg", "jpg", "png", "svg", "blob");
// Allowed mime types.
$allowedMimeTypes = array("image/gif", "image/jpeg", "image/pjpeg", "image/x-png", "image/png", "image/svg+xml");
// Validate image.
if (!in_array(strtolower($mimeType), $allowedMimeTypes) || !in_array(strtolower($extension), $allowedExts)) {
throw new \Exception("File does not meet the validation.");
}
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
$fullNamePath = dirname(__FILE__) . $fileRoute . $name;
// Check server protocol and load resources accordingly.
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != "off") {
$protocol = "https://";
} else {
$protocol = "http://";
}
// Save file in the uploads folder.
move_uploaded_file($tmpName, $fullNamePath);
// Generate response.
$response = new \StdClass;
$response->link = $protocol.$_SERVER["HTTP_HOST"].dirname($_SERVER["PHP_SELF"]).$fileRoute . $name;
// Send response.
echo stripslashes(json_encode($response));
} catch (Exception $e) {
// Send error response.
echo $e->getMessage();
http_response_code(404);
}
?>
delete_image.php :
<?php
try {
$response = FroalaEditor_Image::delete($_POST['src']);
echo stripslashes(json_encode('Success'));
}
catch (Exception $e) {
http_response_code(404);
}
?>
I didn't find any other tutorial in this field and the official site tutorial was not enough.
I tried for a whole day, but it didn't work.
I sincerely appreciate your help.

Upload image on CKEditor 4, The image has been uploaded successfully, but the image cannot be displayed

Previously I tried to upload images to the server using CKEditor 4. The results went into the "images/" directory. However, the image cannot be displayed, and what is stored in the database is:
<figure class="easyimage easyimage-full"><img alt="" src="data:image/gif;base64,R0lGODlhDgAOAIAAAAAAAP///yH5BAAAAAAALAAAAAAOAA4AAAIMhI+py+0Po5y02qsKADs=" width="14" />
<figcaption>adada</figcaption>
</figure>
Here my upload controller:
public function upload_image(Request $request)
{
if($request->hasFile('upload')) {
$originName = $request->file('upload')->getClientOriginalName();
$fileName = pathinfo($originName, PATHINFO_FILENAME);
$extension = $request->file('upload')->getClientOriginalExtension();
$fileName = $fileName.'_'.time().'.'.$extension;
$request->file('upload')->move(public_path('images'), $fileName);
$CKEditorFuncNum = $request->input('CKEditorFuncNum');
$url = asset('images/'.$fileName);
$msg = 'Image uploaded successfully';
$response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
#header('Content-type: text/html; charset=utf-8');
echo $response;
}
}
javascript ckeditor
CKEDITOR.replace('pertanyaan',{
language:'en-gb',
height: 100,
uiColor: '#75b251',
filebrowserUploadUrl: "{{route('adm.akademik.image.upload', ['_token' => csrf_token() ])}}",
filebrowserUploadMethod: 'form',
});

Upload on server image html2canvas

I have this js :
$.ajax({
url: 'ajaxfile.php',
type: 'POST',
data: {
image: base64URL
},
success: function(data){
console.log(data);
$.notify("info", "Upload successfully");
},
error: function () {
$.notify("Error on image upload");
}
});
PHP code :
<?php
$image = $_POST['image'];
$location = "src/upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = "screenshot_".uniqid().'.png';
$file = $location . $filename;
file_put_contents($file, $image_base64);
return [
'status' => true
]
?>
The call is done (I saw in browser console) but on console.log I have the code php returned. Seems that nothing happen, the code php is not implemented. Have you an idea ? Thx in advance and sorry for my english
I put an image with the error
file_put_contents() returns false on failure, so you could assign it to a variable and use that to determine your status like so:
<?php
$image = $_POST['image'];
$location = "src/upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = "screenshot_".uniqid().'.png';
$file = $location . $filename;
$imageData = file_put_contents($file, $image_base64);
if ($imageData !== false) {
echo "success";
} else {
http_response_code(500);
die();
}
?>

add files in to webroot/files

I have a problem, I have view file, but how to save these uploads in to webroot/files. Im using CakePHP:
This is my uploadfile.ctp
echo $this->Form->create('YourModel', array('type' => 'file','enctype'=>'multipart/form-data'));
echo $this->Form->input('files.', array('type' => 'file', 'multiple'));
echo $this->Form->end('Submit');
I dont know where to start in Controller, I really need these files in to webroot/files, thankyou !
At the moment I have in Controller:
public function uploadFile() {
if ($this->request->is('UploadFile')) {
$tmp_name=$this->request->data['UploadFile']['image'];
$filename = time().$this->request->data['UploadFile']['image']['name'];
if (move_uploaded_file($tmp_name['tmp_name'],WWW_ROOT."/files".$filename)) {
} else {
$this->Session->setFlash('There was a problem uploading file. Please try again.','default',array('class'=>'alert alert-danger'));
}
}
}
UPDATE
Now I have updated view file and updated Controller, where I want to upload multiple files, but only one file going in to files folder.
View file:
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[files]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
Controller File:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data['files'];
print_r($this->data['files']); die;
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($uploadData['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
and this Javascript:
$(document).ready(function() {
var max_fields = 3;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[files]' id='uploadFilefiles'/><a href='#' class='remove_field'>Kustuta</a></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
How I can upload all 3 files in to webroot/files folder ?
try this code , this is a demo code and its is work on my server
<div class="col-sm-12">
<?php echo $this->Form->file('Feature.image.',array('class'=>'form-control','label'=>false,'div'=>false,'required','multiple'));?>
</div>
if ($this->request->is('post')) {
$data=$this->request->data['Feature']['image'];
foreach ($data as $key => $value) {
$this->request->data['Feature']['image'][$key]['name'];
$tmp_name=$this->request->data['Feature']['image'][$key];
$filename = time().$this->request->data['Feature']['image'][$key]['name'];
if (move_uploaded_file($tmp_name['tmp_name'],WWW_ROOT."/img/feature/".$filename)) {
$updatefile= $this->Feature->updateAll(
array('Feature.image' => "'$filename'"),
array('Feature.id' => $id,'Feature.userid'=>$this->Session->read('Auth.User.id'))
);
if($updatefile==1){
$file = new File(WWW_ROOT . 'img/feature/'.$featuredata['Feature']['image'], false, 0777);
if($file->delete()) {
$this->Session->setFlash('File uploaded successfuly uploaded.','default',array('class'=>'alert alert-success'),'success');
return $this->redirect(array('controller'=>'Users','action'=>'featureshow')) ;
}
}
} else {
$this->Session->setFlash('There was a problem uploading file. Please try again.','default',array('class'=>'alert alert-danger'));
}
}
}
No, of course you do not need a table.
I guess you are looking for something like this in your controller:
foreach($this->request->data['files'] as $file){
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'uploads/' . $uuid . '.jpg');
}
Use this:-
$uploadedFile = $this->request->params['form']['uploadCsv']['tmp_name'];
$dir = WWW_ROOT . 'files/';
if ( !is_dir( $dir ) ) {
mkdir($dir);
chmod( $dir , 777);
}
$fileName = 'file_' . date( 'Y_m_d_h_i_s', time() );
move_uploaded_file( $uploadedFile, $dir. $fileName . '.csv' );
This is a sample code which works on my server, and should work for you as well

Screenshot of a div with html2canvas. Sent to php, saved: Corrupted image

I generate the canvas and pass it to php so:
$('body').on('click','#save_image',function(){
html2canvas($('.myImage'), {
onrendered: function(canvas) {
//$('.imageHolder').html(canvas);
var dataURL = canvas.toDataURL("image/png");
// $('.imageHolder').append('<img src="'+dataURL+'" />');
$('.imageHolder').html('Generating..');
$.post('image.php',{image: dataURL},function(data){
$('.imageHolder').html(data);
});
}
});
});
image.php:
<?
$image = $_POST['image'];
echo "<img src='$image' alt='image' />";
$decoded = str_replace('data:image/png;base64,','',$image);
$name = time();
file_put_contents("/home/toni005/public_html/toniweb.us/div2img/" . $name . ".png", $decoded);
echo '<p>Download</p>';
?>
download.php:
<? $file = $_GET['img'];
header('Content-Description: File Transfer');
header("Content-type: image/jpg");
header("Content-disposition: attachment; filename= ".$file."");
readfile($file);
?>
The thing is that the image is generated, when I click the download link the download is forzed but the image cannot be opened (seems to be corrupted)
What am I missing?
It can be tested here: http://toniweb.us/div2img/
You should probably base64_decode() the data URL. It even says it in the URL itself: data:image/png;base64,...
$decoded = base64_decode(str_replace('data:image/png;base64,', '', $image));

Categories