grapesjs how to disable embedAsBase64? - javascript

I try to disable grapesjs embedAsBase64 on the image insert without success!
From this :
<img id="irik" data-gjs-type="image" draggable="true"
src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3R5bGU9ImZpbGw6IHJnYmEoMCwwLDAsMC4xNSk7IHRyYW5zZm9ybTogc2NhbGUoMC43NSkiPgogICAgICAgIDxwYXRoIGQ9Ik04LjUgMTMuNWwyLjUgMyAzLjUtNC41IDQuNSA2SDVtMTYgMVY1YTIgMiAwIDAgMC0yLTJINWMtMS4xIDAtMiAuOS0yIDJ2MTRjMCAxLjEuOSAyIDIgMmgxNGMxLjEgMCAyLS45IDItMnoiPjwvcGF0aD4KICAgICAgPC9zdmc+" class="gjs-plh-image">
To this :
<img id="irik" data-gjs-type="image" draggable="true"
src="https://avatars.githubusercontent.com/u/11614725?s=52&v=4"
class="gjs-plh-image">
this its my code but still not works!! please help!
var editor = grapesjs.init({
height: '100%',
container : '#gjs',
fromElement: true,
showOffsets: true,
embedAsBase64: false,
assetManager: {
storageType : '',
embedAsBase64: false,
// assets: images
custom: true,
},
});

assetManager: {
storageType : '',
storeOnChange : true,
storeAfterUpload : true,
upload: 'images',
assets : [ ],
uploadFile: function(e) {
var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
var formData = new FormData();
for(var i in files){
formData.append('file-'+i, files[i]) //containing all the selected images from local
}
$.ajax({
url: 'upload_image.php',
type: 'POST',
data: formData,
contentType:false,
crossDomain: true,
dataType: 'json',
mimeType: "multipart/form-data",
processData:false,
success: function(result){
var myJSON = [];
$.each( result['data'], function( key, value ) {
myJSON[key] = value;
});
var images = myJSON;
editor.AssetManager.add(images);
}
});
},
},
upload_image.php:
if($_FILES)
{
$resultArray = array();
foreach ( $_FILES as $file){
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];
if ($file['error'] != UPLOAD_ERR_OK)
{
error_log($file['error']);
echo JSON_encode(null);
}
$uploadDir = "../images/";
$targetPath = $uploadDir. $fileName;
move_uploaded_file($tmpName, $targetPath);
$finalDir = "../images/";
$finalPath = $finalDir. $fileName;
$result=array(
'name'=>$fileName,
'type'=>'image',
'src'=>$finalPath,
'height'=>350,
'width'=>250
);
array_push($resultArray, $result);
}
$response = array( 'data' => $resultArray );
echo json_encode($response);
}

Related

How to check that file is not selected in Croppie

I use croppie to crop photos on my website. I am able to crop and upload the image. But when I try to crop and upload without selecting an image, a black image is being uploaded. So how do I validate if the file upload is empty? (Note: I use Codeigniter)
HTML:
<div class="form-group">
<div id="upload-image"></div>
</div>
<div class="form-group">
<label for="">Select profile image:</label>
<input type="file" id="images" class="form-control">
<button class="btn btn-success cropped_image help-block"><i class="fa fa-floppy-o"></i> Save</button>
</div>
JS:
$image_crop = $('#upload-image').croppie({
enableExif: true,
viewport: {
width: 342,
height: 192,
type: 'square'
},
boundary: {
width: 380,
height: 250
}
});
$('#images').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$image_crop.croppie('bind', {
url: e.target.result
}).then(function(){
// console.log('<?php echo base_url() ?>');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.cropped_image').on('click', function (ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: { width: 1366, height: 768 }
}).then(function (response) {
$.ajax({
url: "<?php echo base_url() ?>Light/upload_home_bg",
type: "POST",
data: {"image":response},
success: function (data) {
alert(data);
$(location).attr('href','<?php echo base_url() ?>Light/home');
// html = '<img src="' + response + '" />';
// $("#upload-image-i").html(html);
}
});
});
});
PHP:
public function upload_home_bg()
{
$path = 'uploads/'.$this->data['account']->username.'/';
$croped_image = $_POST['image'];
list($type, $croped_image) = explode(';', $croped_image);
list(, $croped_image) = explode(',', $croped_image);
$croped_image = base64_decode($croped_image);
$image_name = time().'.png';
// upload cropped image to server
file_put_contents($path.$image_name, $croped_image);
$query = $this->db->query("select * from contents where user_id = '$this->user_id' and id = '$this->id' and meta_key = 'home_background_image'");
if ($query->num_rows() > 0)
{
$data['home_bg'] = $query->row();
$Bg = [
'value' => base_url().$path.$image_name
];
if ($this->Lights->update_home_background_image($Bg,$this->user_id,$data['home_bg']->content_id))
{
echo "Image successfully updated!";
}
}
else
{
$Bg = [
'user_id' => $this->user_id,
'id' => $this->id,
'business_name' => $this->BusinessName,
'meta_key' => 'home_background_image',
'content_title' => '',
'description' => '',
'value' => base_url().$path.$image_name
];
if ($this->db->insert('contents',$Bg))
{
echo "Image successfully uploaded!";
}
}
}
I tried doing this to check if the user selected an image:
if (!empty($_POST['image'])) {
# code...
}
But there are data being passed regardless if the user selected an image or not. Here is the data being passed (on the alert window): https://i.stack.imgur.com/DtqFD.png
Thanks in advance!
Okay. I finally managed to come up with a solution. What I did was to pass another value on my ajax var file_input = $('#images').val(); which gets the value of my file upload input.
JS:
$('.cropped_image').on('click', function (ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: { width: 1366, height: 768 }
}).then(function (response) {
var file_input = $('#images').val();
$.ajax({
url: "<?php echo base_url() ?>Light/upload_home_bg",
type: "POST",
data: {"image":response,"file":file_input},
success: function (data) {
alert(data);
$(location).attr('href','<?php echo base_url() ?>Light/home');
}
});
});
});
Then on my php file, I check if the file is empty or not:
if (!empty($this->input->post('file')))
{
//Upload code
}
else
{
//Prompt user to select an image
}
late to the party - similar problem. I added this before the ajax:
...}).then(function (response) {
if(response.length < 2000){
if(! confirm("Did you load an image? It looks too small\n"+ response.length)) return;
}
FWIW an empty image for me is of length 1971

SQL DELETE not work

Good morning, everyone,
I have a problem with my script I can't figure out how to make a feature. I'll explain:
I'm using the outlook API I get my mails, send them to my bdd in an inbox table. I then have some buttons that allow to send my mails in other table (to do/ Urgent/Archive).
The problem is that I want to delete the inbox data when I send an email to another table.
I have a view file (I don't put it in I don't think it's useful)
A file with my AJAX request:
window.onload = function(item){
console.log("********************TEST_INSERT*********************");
for($i = 0; $i <= 2; $i++){
console.log("after for");
console.log($i);
$thisInput = document.getElementsByClassName('from_1')[$i].textContent;
$thisSub = document.getElementsByClassName('subject_1')[$i].textContent;
$thisRecei = document.getElementsByClassName('received_1')[$i].textContent;
$thisPreview = document.getElementsByClassName('bodypreview_1')[$i].textContent;
$thisBody_2 = document.getElementsByClassName('body_2')[$i].textContent;
console.log("*********************");
console.log($thisInput);
console.log($thisSub);
console.log($thisRecei);
console.log($thisPreview);
console.log($thisBody_2);
console.log("*********************");
console.log("**********************");
console.log("******STOCK************");
console.log("**********************");
//var $input = $(item).closest(".emailBody").find(".from_1")[0].innerHTML;
//var $sub = $(item).closest(".emailBody").find(".subject_1")[0].innerHTML;
//var $recei = $(item).closest(".emailBody").find(".received_1 em")[0].innerHTML;
//var $preview= $(item).closest(".emailBody").find(".bodypreview_1 em")[0].innerHTML;
//var $body_2 = $(item).closest(".emailBody").find(".body_2 em")[0].innerHTML;
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general.php',
type: 'POST',
data: {info: 'stock_mail_inbox', input: $thisInput, sub: $thisSub, recei: $thisRecei, preview: $thisPreview, body : $thisBody_2},
success: function() {
console.log("OK");
}
});
};
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general.php',
type: 'POST',
dataType: 'html',
data: {info: 'display_mail'},
success: function(html) {
console.log("OKok");
$('#display_mail').html(html);
}
});
};
function btn_a_faire(item){
console.log("**********************");
console.log("******ajax A FAIRE************");
console.log("**********************");
var $thisInput = $(item).closest(".emailBody").find(".from_1")[0].innerHTML;
var $thisSub = $(item).closest(".emailBody").find(".subject_1")[0].innerHTML;
var $thisRecei = $(item).closest(".emailBody").find(".received_1 em")[0].innerHTML;
var $thisPreview = $(item).closest(".emailBody").find(".bodypreview_1 em")[0].innerHTML;
var $thisBody_2 = $(item).closest(".emailBody").find(".body_2 em")[0].innerHTML;
console.log($thisBody_2);
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general_2.php',
type: 'POST',
data: {info: 'insert_to_db_a_faire', input: $thisInput, sub: $thisSub, recei: $thisRecei, preview: $thisPreview, body : $thisBody_2},
success: function() {
console.log("OK");
}
});
};
function btn_urgent(item){
console.log("**********************");
console.log("******ajax URGENT************");
console.log("**********************");
var $thisInput = $(item).closest(".emailBody").find(".from_1")[0].innerHTML;
var $thisSub = $(item).closest(".emailBody").find(".subject_1")[0].innerHTML;
var $thisRecei = $(item).closest(".emailBody").find(".received_1 em")[0].innerHTML;
var $thisPreview = $(item).closest(".emailBody").find(".bodypreview_1 em")[0].innerHTML;
var $thisBody_2 = $(item).closest(".emailBody").find(".body_2 em")[0].innerHTML;
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general_3.php',
type: 'POST',
data: {info: 'insert_to_db', input: $thisInput, sub: $thisSub, recei: $thisRecei, preview: $thisPreview, body : $thisBody_2},
success: function() {
console.log("OK");
}
});
}
function btn_archive(item){
console.log("**********************");
console.log("******ajax URGENT************");
console.log("**********************");
var $thisInput = $(item).closest(".emailBody").find(".from_1")[0].innerHTML;
var $thisSub = $(item).closest(".emailBody").find(".subject_1")[0].innerHTML;
var $thisRecei = $(item).closest(".emailBody").find(".received_1 em")[0].innerHTML;
var $thisPreview = $(item).closest(".emailBody").find(".bodypreview_1 em")[0].innerHTML;
var $thisBody = $(item).closest(".emailBody").find(".body_2 em")[0].innerHTML;
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general_4.php',
type: 'POST',
data: {info: 'insert_to_db_archive', input: $thisInput, sub: $thisSub, recei: $thisRecei, preview: $thisPreview, body : $thisBody_2},
success: function() {
console.log("OK");
}
});
}
And I have 4 files that process INSERTs in my bdd (proccess_general. php/proccess_general_2...):
Proccess_general.php:
$info = $_POST['info'];
$thisInput= $_POST['input'];
$thisRecei= $_POST['recei'];
$thisSub= $_POST['sub'];
$thisPreview= $_POST['preview'];
$thisBody= $_POST['body'];
stock_mail_inbox($thisInput, $thisSub, $thisRecei, $thisPreview, $thisBody);
function stock_mail_inbox($thisInput, $thisSub, $thisRecei, $thisPreview, $thisBody){
global $wpdb;
$wpdb->insert(
'inbox', //table name
array(
'id' => '',
'from_mail' => $thisInput,
'subject' =>$thisSub,
'recei' => $thisRecei,
'preview' =>$thisPreview,
'body' => $thisBody,
), //columns
array(
'%d',
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
}
proccess_general_2.php:
$info = $_POST['info'];
$thisInput= $_POST['input'];
$thisRecei= $_POST['recei'];
$thisSub= $_POST['sub'];
$thisPreview= $_POST['preview'];
$thisBody= $_POST['body'];
insert_to_db_a_faire($thisInput, $thisSub, $thisRecei, $thisPreview, $thisBody);
function insert_to_db_a_faire($thisInput, $thisSub, $thisRecei, $thisPreview, $thisBody){
global $wpdb;
$wpdb->insert(
'a_faire', //table name
array(
'id' => '',
'from_mail' => $thisInput,
'subject' =>$thisSub,
'recei' => $thisRecei,
'preview' =>$thisPreview,
'body' => $thisBody,
), //columns
array(
'%d',
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
$wpdb->prepare('DELETE FROM `inbox` WHERE recei = $thisRecei');
}
In proccess_general_2 I added a DELETE but it doesn't work. When I test my request in phpmyadmin it works but once in my code nothing works.
I hope to have been clear, I remain available if necessary.
Thank you all for a great day.
You should have something like execute( ) after preparing. Try this (or find the equivalent, according to what tools you use)
$wpdb->prepare('DELETE FROM `inbox` WHERE recei = $thisRecei');
$wpdb->execute();

ajax passing two forms with codeigniter

I have a problem related with passing two forms in ajax to my controller code igniter. My first form is a file var formData = new FormData($('#form-upload')[0]);
and my second form consists of profile data $('#frm_patientreg').serialize()
now my problem is how can I pass these two forms in ajax?
I already tried this code:
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: $('#frm_patientreg').serialize()+formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
else {
alert("No File Selected");
}
but it returns me an error.
When I tried to pass data:formData, only, my image file was successfully uploaded, but when I add the $('#frm_patientreg').serialize(), it outputs an error. How can I pass both forms?
Here is my controller:
public function addpatient() {
$config['upload_path'] = './asset/uploaded_images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
if($this->upload->do_upload("file")) {
$upload_data = $this->upload->data();
$file_name = base_url().'asset/uploaded_images/'.$upload_data['file_name'];
$mypatiendid = $this->genpatient_id();
$patient_bday = $this->input->post('pabdate');
$DB_date = date('Y-m-d', strtotime($patient_bday));
$patient_height = $this->input->post('paheight');
$DB_height = $patient_height . " cm";
$patient_weight = $this->input->post('paweight');
$DB_weight = $patient_weight . " kg";
$data = array (
'patient_id' => $mypatiendid,
'patient_fname' => $this->input->post('pafname'),
'patient_mname' => $this->input->post('pamname'),
'patient_lname' => $this->input->post('palname'),
'patient_address' => $this->input->post('paaddress'),
'patient_contact_info' => $this->input->post('pacontact'),
'patient_bday' => $DB_date,
'patient_age' => $this->input->post('paage'),
'patient_height' => $DB_height,
'patient_weight' => $DB_weight,
'patient_sex' => $this->input->post('psex'),
'patient_civil_status' => $this->input->post('pmartialstat'),
'patient_photo' => $file_name,
);
var_dump($data);
}
else {
echo "File cannot be uploaded";
$error = array('error' => $this->upload->display_errors()); var_dump($error);
}
}
Not tested..but try this:
var FormTwo = new FormData();
$('#frm_patientreg input, #frm_patientreg select').each(function(index){
FormTwo.append($(this).attr('name'),$(this).val());
});
FormTwo.append('file', $('#frm_patientreg input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: {formTwo: FormTwo, formOne: formData},
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
change this
data: $('#frm_patientreg').serialize()+formData,
into this
data: $('#frm_patientreg').serialize()+'&'+formData,

Summernote image upload not working

I am having a problem with summernote Image Upload.
My script looks some what like this:
<script>
$(document).ready(function() {
var IMAGE_PATH = 'http://localhost/dist/images/';
$('.summernote').summernote({
height: 300,
callbacks : {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
function uploadImage(image) {
var data = new FormData();
data.append("image",image);
$.ajax ({
data: data,
type: "POST",
url: "uploader.php",
cache: false,
contentType: false,
processData: false,
success: function(url) {
var image = IMAGE_PATH + url;
$('.summernote').summernote('insertImage', image);
},
error: function(data) {
console.log(data);
}
});
}
});
</script>
and uploader.php has following codes:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'images/';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
Image files are uploading successfully to the dir 'images'.
But $('.summernote').summernote('insertImage', image); doesn't append the uploaded Image Link to the editor.
What am i missing ? And yes, i tried alerting the var 'image' and it has the required value.
Use the code below. It should work perfectly
PHP Script
<?php
// include Database connection file
require_once("../../resources/directories.inc.php");
if (isset($_FILES['file']['name'])) {
if (!$_FILES['file']['error']) {
$name = rand(100,1000).'_'.date('Ymd');
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$filename = $name.'.'.$ext;
$destination = '../../uploads/news/'.$filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo BASE_URL.'uploads/news/'.$filename;
} else {
echo 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
?>
JS CODE
$('.summernote_editor').summernote({
tabsize: 2,
height: 400,
spellCheck: true,
toolbar: [
['style', ['style']],
['font', ['bold', 'underline', 'italic', 'superscript', 'subscript', 'clear']],
['fontname', ['fontname','fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['table', ['table']],
['insert', ['link', 'picture', 'video']],
['view', ['fullscreen', 'help', 'undo', 'redo']],
],
callbacks: {
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
}
});
function sendFile(file, editor, welEditable) {
var lib_url = '<?php echo BASE_URL."resources/library/upload_summernote.lib.php"; ?>';
data = new FormData();
data.append("file", file);
$.ajax({
data: data,
type: "POST",
url: lib_url,
cache: false,
processData: false,
contentType: false,
success: function(url) {
var image = $('<img>').attr('src', url);
$('.summernote_editor').summernote("insertNode", image[0]);
}
});
}
you can try :var IMAGE_PATH = 'http://localhost/dist/';
because your php codes :$uploadfile=>'images/xxx.jpg', the html url use the twice images,like ../images/images/xxx.jpg. so summernote image upload not working!
thanks!
it's my codes
<script>
$(document).ready(function() {
var IMAGE_PATH = 'http://localhost:81/summernote-develop/examples/';
$('.summernote').summernote({
height: 300,
callbacks : {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
function uploadImage(image) {
var data = new FormData();
data.append("image",image);
$.ajax ({
data: data,
type: "POST",
url: "uploader.php",
cache: false,
contentType: false,
processData: false,
success: function(url) {
var image = IMAGE_PATH + url;
$('.summernote').summernote('insertImage', image);
//console.log(image);
},
error: function(data) {
console.log(data);
}
});
}
});
</script>
the php codes as same as you.
and codes dir:D:\WWW\summernote-develop\examples\
images dir:D:\WWW\summernote-develop\examples\images

Ajax File Upload - Script Writes garbage in File

i have a Problem with my Ajax-Fileupload Script.
When I upload my Files, the Files are corrupt. When I open the File with Notepad++, i see that there are for example the following Lines:
-----------------------------22998260013704
Content-Disposition: form-data; name="0"; filename="myimage.png"
Content-Type: image/png
filecontent
-----------------------------22998260013704--
When I delete the 3 Lines bevor filecontent und the Line after filecontent, the File is ok.
I have no clue, why these 4 Lines are written to the Files.
I hope that somebody can help me.
Here is my Javascript-Code:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
data = new FormData(),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
console.log(key+" "+value);
file = value;
data.append(key, value);
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- http://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
And here my relevant PHP-Code:
private function copyPutFilesToTmp($directory = "") {
$temp = "xxx";
if (!is_dir($temp)) {
mkdir ($temp, 0777, true);
}
$tmpPath = $temp."/";
$filename = $_SERVER['HTTP_X_FILE_NAME'];
$in = fopen('php://input', 'r');
$ziel = $tmpPath.$filename;
if (!file_exists($ziel)) {
$fileuploadok = true;
$out = fopen($ziel, 'w');
$data = fread($in, 1024);
while($data) {
if ($data != false) {
fwrite($out, $data);
} else {
$fileuploadok = false;
}
$data = fread($in, 1024);
}
fclose($in);
fclose($out);
if ($fileuploadok === FALSE) {
//...
} else {
//...
}
} else {
//...
}
return $answer;
}
I found the problem.
if I sent the file directly as data and not within a FormData it works!
So the right Code is:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
file = value;
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- https://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: file,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
found here: AJAX File Upload with XMLHttpRequest

Categories

Resources