I'm using summernote version 0.8.1 (current).
It's working. But 1 thing I struggle with. Inserting an image, rather than putting base64 dataURL, I want to upload the image to the server and insert the image URL in the database. This is my code:
<script>
$(document).ready(function() {
$('#summernote').summernote({
lang: 'fr-FR',
height: 300,
toolbar : [
['style',['bold','italic','underline','clear']],
['font',['fontsize']],
['color',['color']],
['para',['ul','ol','paragraph']],
['link',['link']],
['picture',['picture']]
],
onImageUpload: function(files, editor, welEditable) {
for (var i = files.lenght - 1; i >= 0; i--) {
sendFile(files[i], this);
}
}
});
function sendFile(file, el) {
var form_data = new FormData();
form_data.append('file',file);
$.ajax ({
data: form_data,
type: "POST",
url: "../up.php",
cache: false,
contentType: false,
processData: false,
success: function(url) {
$(el).summernote('editor.insertImage',url);
}
})
}
});
</script>
I have tested the script up.php and what that does is changing the file name and returning the image's url in the form "../photos/mypicture.jpg".
The problem with the above code is that the ..up.php doesn't even seem to be called. I ran this in Firefox development tools and got no errors or warnings.
I got it working. Here's my code. Using summernote 0.8.1, i.e. current version.
<script>
$(document).ready(function() {
var IMAGE_PATH = 'http://www.path/to/document_root/';
// the exact folder in the document_root
// will be provided by php script below
$('#summernote').summernote({
lang: 'fr-FR', // <= nobody is perfect :)
height: 300,
toolbar : [
['style',['bold','italic','underline','clear']],
['font',['fontsize']],
['color',['color']],
['para',['ul','ol','paragraph']],
['link',['link']],
['picture',['picture']]
],
callbacks : {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
function uploadImage(image) {
var data = new FormData();
data.append("image",image);
$.ajax ({
data: data,
type: "POST",
url: "../up.php",// this file uploads the picture and
// returns a chain containing the path
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>
Here my up.php :
<?php
require('admchir/nettoie.php');
// nettoie.php removes the French special chars and spaces
$image = nettoie($_FILES['image']['name']);
$uploaddir = 'photos/';
// that's the directory in the document_root where I put pics
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo$uploadfile;
} else {
echo "Lo kol kakh tov..."; // <= nobody is perfect :)
}
?>
From looking for this on the internet, I got the impression that summernote changed a lot between the various versions, but didn't find a full working example of the current version. Hope this helps someone.
This is how I integrated it with Codeigniter 3, Summernote 0.8.1:
I am posting my working solution here so that anyone else can get some help or idea on how to implement summernote with image upload in CI 3 with CSRF.
the javascript code:
<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>
<script>
$(document).ready(function () {
$('#content').summernote({
height: 400,
callbacks: {
onImageUpload: function (image) {
sendFile(image[0]);
}
}
});
function sendFile(image) {
var data = new FormData();
data.append("image", image);
//if you are using CI 3 CSRF
data.append("<?= $this->security->get_csrf_token_name() ?>", "<?= $this->security->get_csrf_hash() ?>");
$.ajax({
data: data,
type: "POST",
url: "<?= site_url('summernote-image-upload') ?>",
cache: false,
contentType: false,
processData: false,
success: function (url) {
var image = url;
$('#content').summernote("insertImage", image);
},
error: function (data) {
console.log(data);
}
});
}
});
</script>
the codeigniter part:
//add this line in your routes.php
$route['summernote-image-upload'] = 'welcome/summernote-image-upload';
//now add this method in your Welcome.php Controller:
function summernote_image_upload() {
if ($_FILES['image']['name']) {
if (!$_FILES['image']['error']) {
$ext = explode('.', $_FILES['image']['name']);
$filename = underscore($ext[0]) . '.' . $ext[1];
$destination = './public/images/summernote/' . $filename; //change path of the folder...
$location = $_FILES["image"]["tmp_name"];
move_uploaded_file($location, $destination);
echo base_url() . 'public/images/summernote/' . $filename;
} else {
echo $message = 'The following error occured: ' . $_FILES['image']['error'];
}
}
}
the HTML part:
<textarea name="content" id="content"><?= html_entity_decode(set_value('content')) ?></textarea>
<?= form_error('content') ?>
note if you face issue with CSRF (for any reason), then you can exclude the summernote ajax upload in your config.php file:
$config['csrf_exclude_uris'] = array('summernote-image-upload');
Related
I need to upload multiple files to a server using an ajax call.
Here is the code, every-time I am using it I am getting an upload error. The post is not working in the html side.
Below is the code I have used in html and php.
HTML
<input name="fileToUploadName" id="fileinput0" type='file' />
<input name="fileToUploadName" id="fileinput1" type='file' />
<input name="fileToUploadName" id="fileinput2" type='file' />
JS
function upload(){
var formdata = new FormData();
var image0 = $('#fileinput0')[0].files[0];
if(image0)
formdata.append('fileToUpload[]',image0);
var image1 = $('#fileinput1')[0].files[0];
if(image1)
formdata.append('fileToUpload[]',image1);
var image2 = $('#fileinput2')[0].files[0];
if(image2)
formdata.append('fileToUpload[]',image2);
$.ajax({
url: 'server.php',
type: 'POST',
data: formdata,
async: true,
dataType: "text",
success: function (data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
var p =0;
alert("Error uploading data");
},
cache: false,
contentType: false,
processData: false
});
}
server.php
if(isset($_POST['submit']))
{
$uploaddir = 'uploads/';
foreach ($_FILES['fileToUpload']['error'] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES['fileToUpload']['tmp_name'][$key];
$name = $_FILES['fileToUpload']['name'][$key];
$uploadfile = $uploaddir . basename($name);
if (move_uploaded_file($tmp_name, $uploadfile))
{
echo "Success: File ".$name." uploaded.<br/>";
}
else
{
echo "Error: File ".$name." cannot be uploaded.<br/>";
}
}
}
}
But every time I am getting an upload error.
Your problem is here, in your JavaScript file:
url: 'serever.php';
This should be
url: 'server.php';
This is, however, a simple typographical error.
My onImageUpload in summer note jquery plugin is not working.
for upload image in some folder different place then summernote default location
how can i handle this ?!
index.php
<textarea id="summernote" name="contents"></textarea>
<script>
$('#summernote').summernote({
tabsize: 2,
height: 200,
focus: true,
callbacks: {
onChange: function(contents, $editable) {
console.log('onChange:', contents, $editable);
}
}
});
$('#summernote').on('summernote.image.upload', function(we, contents, $editable) {
data = new FormData ();
data.append("file",file);
$.ajax({
url: "summernote_upload.php",
type: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
});
$summernote.summernote('insertNode', imgNode);
});
</script>
summernote_upload.php
require_once ('./../../lib/curl_setup.php'); // curl json&token
$data_array = array(
"request" => array(
"image" => "this upload file/base64"
),
);
$make_call = callAPI('POST', '/api/v2/admin/products/images', json_encode($data_array));
$response = json_decode($make_call, true);
//$errors = $response['response']['errors'];
//$data = $response['response']['data'][0];
print_r($response);exit;
However, summernote_upload.php works well.
The response is:
{
"image": {
"shop_no": 1,
"path": "/web/upload/NNEditor/20180408/b69c819e36b4abc3f393b731829ab747.gif"
}
}
I need to solve the index.php.
first you must catch the upload image event
and dont allow to summernote add it automatically
callbacks: {
onImageUpload: function(files, editor, $editable) {
console.log('onImageUpload');
sendFile(files[0],editor,$editable);
}},
then you must handle image upload with json yourself.
there is a function for this:
function sendFile(file,editor,welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
url: "uploader.php",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
// alert(data);
$('#summernote10').summernote("insertImage", data, 'filename');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus+" "+errorThrown);
}
});
}
and in server side you can save the file
$allowed = array('png', 'jpg', 'gif','jpeg');
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
$newFileAddress = '../files/-'.rand(1000).'.'.$extension;
if(move_uploaded_file($_FILES['file']['tmp_name'],$newFileAddress)){
echo $newFileAddress;
exit;
}
}
by return the file path on server you can insert it on summer note easily
I have a form in which I have a field for name and dropzone. So if I go with simple one like to upload files in main upload folder then it is working but I want to upload files in child folder like I am getting folder name through <input type="text" name="name" /> and on upload file should go to new generated folder.
HTML:
<input type="text" name="name" class="form-control fl_name" />
<div class="dropzone"></div>
JS:
// CREATE FOLDER FOR FILE UPLOADS
$('.name-alert').hide();
$('.fl_name').on('change', function() {
var fl_name = 'name='+ $(this).val();
var fl_url = $(this).closest('form').attr('action');
$.ajax({
type: 'POST',
url: fl_url,
data: fl_name,
cache: false,
success: function(result){
if (result == '0') {
$('.name-alert').slideDown();
setTimeout(function() {
$('.name-alert').slideUp();
}, 2000);
}
}
});
});
// CREATE DROPZONE ENVIORMENT
var myDropzone = new Dropzone('div.dropzone', {
url: "http://localhost/build/assets/php/customer-query.php",
addRemoveLinks: true,
init: function() {
this.on('success', function( file, resp ){
var fl_name = 'name='+ $('.fl_name').val();
var fl_url = 'http://localhost/build/assets/php/customer-query.php';
$.ajax({
type: 'POST',
url: fl_url,
data: fl_name,
cache: false,
success: function(result){
console.log(result);
}
});
});
},
});
PHP:
// Create Folder On Input Field Change
$fname = $_POST['name'];
if (!file_exists('../uploads/'.$fname.'/')) {
mkdir('../uploads/'.$fname.'/', 0777, true);
} else {
echo '0';
}
// Upload Files
$fl_name = $_POST['name'];
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '../uploads/'.$fl_name.'/';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) .$ds. $storeFolder .$ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
in my code files are still uploading in main folder instead of new folders.
Thanks
Your "data" in the ajax call doesn't look like a json object. Try changing it to:
$.ajax({
type: 'POST',
url: fl_url,
data: {'name':fl_name},
dataType: "json",
cache: false,
success: function(result){
console.log(result);
}
});
See Passing data with jquery ajax if you need a further example on passing data with json via ajax
You may also be missing the following in your php file to read the json input:
$inputJSON = file_get_contents("php://input");
$result = json_decode($inputJSON,TRUE);
in which case you need to change
$fname = $_POST['name'];
to
$fname = $result['name'];
I have the below script that loads a json editor. The path to the json file that should be loaded is stored in a php var called $filePath. This works well however instead of loading a pre-determined json file I would like to have a dropdown list of all files in a specified directory ($dirPath) that the user can choose from. Any help would be greatly appreciated.
<?php global $filePath, $dirPath; ?>
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {
mode: 'view',
modes: ['code', 'text', 'view'], // allowed modes
onError: function (err) {
alert(err.toString());
},
onModeChange: function (newMode, oldMode) {
console.log('Mode switched from', oldMode, 'to', newMode);
}
};
var editor = new JSONEditor(container, options);
// set json
document.getElementById('setJSON').onclick = function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "<?php echo $filePath; ?>",
'dataType': "json",
'success':
function (data) { json = data; }
});
editor.set(json);
};
</script>
I am trying to upload a image to Database using Javascript on client and PHP on server.
first image is selected from the gallery.
after zooming and cropping the image is passed to database
The Problem is when iam trying to submit the cropped image value is not passed to the php the actual uploaded input "File" Value is Being Passed, but i need the cropped areas value to be passed to PHP.
For testing purpose if all the js are required i can provide it.
Js: This Crops the image
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 40,
});
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
HTML:
<form id="uploadForm" class="image-editor">
<input type="file" class="cropit-image-input">
<!-- .cropit-image-preview-container is needed for background image to work -->
<div class="cropit-image-preview-container">
<div class="cropit-image-preview"></div>
</div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<input type="submit" class="export">Export</input >
</form>
Ajax: ajax sends the data to php
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});
});
PHP:
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$mysl = mysqli_connect("localhost", "root", "root","test");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "UPDATE output_images SET imageType ='{$imageProperties['mime']}',imageData= '{$imgData}' WHERE imageId='16'";
$current_id = mysqli_query($mysl,
$sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());;
if(isset($current_id)) {
echo "done";
}
}
}
First, take a look at this: Can I pass image form data to a PHP function for upload?
I think the issue is here: var imageData = $('.image-editor').cropit('export');. Since this new image is never a part of the form, there is no way to pass it via AJAX.
In your JS/JQuery, I would advise:
var imageData = '';
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 40,
});
$('.export').click(function() {
imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
var fd = new FormData(this);
fd.append( imageData, file );
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});
});
EDIT
In your example, you never defined a name or id attribute for your input, so there would be no way for PHP to index the $_FILES global. Could try $_FILES[0]. I would advise assigning that in your form or when you post it.
You can adjust the myFormData.append(name, file, filename);. So it would be:
fd.append('crop-image', imageData, 'crop-image.jpg');
Then in PHP, you call it using $_FILES['crop-image']. If you want to pass the file name from the form:
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
var fd = new FormData(this);
var origFileName = $("input[type='file']").val();
var startIndex = (origFileName.indexOf('\\') >= 0 ? origFileName.lastIndexOf('\\') : origFileName.lastIndexOf('/'));
var filename = origFileName.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0){
filename = filename.substring(1);
}
var cropFileName = "crop-" + filename;
fd.append('crop-image' imageData, cropFileName );
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});