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
Related
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);
}
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
Does anyone have a good example of the code to use Summernote 0.8.8 that uploads images to a directory on the server (not as base64)? I tried some of the older posted results(they might have worked with older versions of Summernote),but nothing seams to work for me. I'm not strong on Java, so I'm not sure how to fix the issue.
Summernote's web example is
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
$summernote.summernote('insertNode', imgNode);
}
}
});
$('#summernote').on('summernote.image.upload', function(we, files) {
$summernote.summernote('insertNode', imgNode);
});
But this does not work, as the image does not 'upload' it is still in Base64. This does work for me, as it loads too slow. Thanks!
FOR SUMMERNOTE 0.88+
I Tested it with these CDN
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote.min.js"></script>
JAVASCRIPT
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: "300px",
dialogsInBody: true,
callbacks: {
onImageUpload: function(files) {
uploadFile(files[0]);
}
}
});
});
function uploadFile(file) {
data = new FormData();
data.append("file", file);
$.ajax({
data: data,
type: "POST",
url: "upload_url_path", //replace with your url
cache: false,
contentType: false,
processData: false,
success: function(url) {
$('#summernote').summernote("insertImage", url);
}
});
}
</script>
PHP SAMPLE CODE FOR UPLOAD
<?php
$allowed = array( 'png', 'jpg', 'gif' );
if( isset($_FILES['file']) && $_FILES['file']['error'] == 0 ) {
$extension = pathinfo( $_FILES['file']['name'], PATHINFO_EXTENSION );
if( !in_array( strtolower( $extension ), $allowed ) ) {
echo 'AN ERROR OCCURED - INVALID IMAGE';
exit;
}
if( move_uploaded_file( $_FILES['file']['tmp_name'], 'assets/images/'.$_FILES['file']['name'] ) ) {
echo base_url().'assets/images/'.$_FILES['file']['name']; // echo absolute file_url
exit;
}
}
echo 'AN ERROR OCCURED';
exit;
?>
https://summernote.org/deep-dive/#onimageupload
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
here is the my javascript code.
$(document).ready(function() {
$("#fileUpload2").fileUpload({
'method' : 'GET',
'uploader': 'js/uploadify/uploader.swf',
'cancelImg': 'js/uploadify/cancel.png',
'script': 'model/Properties/Manage Properties/add_files.php',
'folder': 'files',
'multi': true,
'buttonText': 'Browse',
'checkScript': 'js/uploadify/check.php',
'displayData': 'speed',
'simUploadLimit': 22,
'OnUploadEvent' : function(dom){
$(dom)('#fileUpload2').uploadifySettings(
'scriptData',
{'ext':$('#osDeed').val(), 'ext2':'bab'}
);
}
});
});
this code only can send static data but not form data i dont know. i am just stuck please help.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//uploadify function
$("#file_upload").uploadify({
'uploader': 'uploadify.swf',
'script': 'uploadify.php',
'cancelImg': 'cancel.png',
'folder': 'photos', //folder where images to be uploaded
'auto': false, // use for auto upload
'multi': true,
'queueSizeLimit': 6,
'buttonImg': 'images/upload.png',
'width': '106',
'height': '33',
'wmode': 'transparent',
'method': 'POST',
'scriptData': {'myid':post_id}, //you can post the id here
'onQueueFull': function(event, queueSizeLimit) {
alert("Please don't put anymore files in me! You can upload " + queueSizeLimit + " files at once");
return false;
},
'onComplete': function(event, ID, fileObj, response, data) {
$("#uploadfiles").append(response+",");
},
'onAllComplete': function(response, data) {
showAll();
}
});
</script>
scriptData is used to send the post_id to the php file
uploadify.php
if (!empty($_FILES)) {
$post_id = $_POST['myid'];
include_once "config.php"; //connect to database
//use this when uploading images into a folder
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$fna = $_FILES['Filedata']['name'];
$targetFile = str_replace('//','/',$targetPath) . $fna;
move_uploaded_file($tempFile,$targetFile);
//folder upload end
$name2 = mysql_real_escape_string($_FILES['Filedata']['name']);
$data2 = mysql_real_escape_string(file_get_contents($_FILES['Filedata']['tmp_name']));
$size2 = intval($_FILES['Filedata']['size']);
$db->query("INSERT INTO tbl_files SET post_id='$post_id', filename='$name2', file_data='$data2'");
}
First thing is you should change your method from 'GET' to 'POST', just like
method = 'post'
You can send any value via post to server side via formData property, and then update it "onUploadStart" event of uploadify
Your final code will look like
$(document).ready(function() {
$("#fileUpload2").uploadify({
'formData': {
'ext': '',
'ext2':''
},
'method' : 'post',
'uploader': 'js/uploadify/uploader.swf',
'cancelImg': 'js/uploadify/cancel.png',
'script': 'model/Properties/Manage Properties/add_files.php',
'multi': true,
'buttonText': 'Browse',
'checkScript': 'js/uploadify/check.php',
'onUploadStart': function (file) {
$('#file_upload').uploadify('settings', 'formData', {'ext': $('#osDeed').val(), 'ext2':'bab'});
},
}
});
});