summernote 0.8.8 onimageupload example - javascript

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

Related

How to upload an image to server directory using ajax?

I have this ajax post to the server to send some data to an SQL db :
$.ajax({
method: "POST",
url: "https://www.example.com/main/public/actions.php",
data: {
name: person.name,
age: person.age,
height: person.height,
weight: person.weight
},
success: function (response) {
console.log(response)
}
})
in the server i get this data with php like this :
<?php
include "config.php";
if(isset ( $_REQUEST["name"] ) ) {
$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];
$sql = "INSERT INTO persons ( name, age, height, weight )
VALUES ( '$name', '$age', '$height', '$weight' )";
if ($conn->query($sql) === TRUE) {
echo "New person stored succesfully !";
exit;
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit;
}
};
?>
I also have this input :
<input id="myFileInput" type="file" accept="image/*">
and in the same directory as actions.php i have the folder /images
How can i include an image ( from #myFileInput ) in this ajax post and save it to the server using the same query in php ?
I have searched solutions in SO but most of them are >10 years old,i was wondering if there is a simple and modern method to do it,i'm open to learn and use the fetch api if its the best practice.
You should use the formData API to send your file (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)
I think what you are looking for is something like that:
var file_data = $('#myFileInput').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://www.example.com/main/public/actions.php',
contentType: false,
processData: false, // Important to keep file as is
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(response);
}
});
jQuery ajax wrapper has a parameter to avoid content processing which is important for file upload.
On the server side, a vrey simple handler for files could look like this:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
via ajax FormData you can send it . refer here . Note : data: new FormData(this) - This sends the entire form data (incldues file and input box data)
URL : https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/
$(document).ready(function(e) {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if (data == 'invalid') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
}));
});
If you are not averse to using the fetch api then you might be able to send the textual data and your file like this:
let file=document.querySelector('#myFileInput').files[0];
let fd=new FormData();
fd.set('name',person.name);
fd.set('age',person.age);
fd.set('height',person.height);
fd.set('weight',person.weight);
fd.set('file', file, file.name );
let args={// edit as appropriate for domain and whether to send cookies
body:fd,
mode:'same-origin',
method:'post',
credentials:'same-origin'
};
let url='https://www.example.com/main/public/actions.php';
let oReq=new Request( url, args );
fetch( oReq )
.then( r=>r.text() )
.then( text=>{
console.log(text)
});
And on the PHP side you should use a prepared statement to mitigate SQL injection and should be able to access the uploaded file like so:
<?php
if( isset(
$_POST['name'],
$_POST['age'],
$_POST['height'],
$_POST['weight'],
$_FILES['file']
)) {
include 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
move_uploaded_file($tmp,'/path/to/folder/'.$name );
#add file name to db????
$sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssss',$name,$age,$height,$weight);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
$conn->close();
exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
};
?>

Symfony 4.4 - Summernote editor upload base64 images to server

Pretty common problem with a lot of answers here but couldn't make it work for my Symfony 4 application. I tried to debug my action with dump() and die(), it doesn't even enter the action and I think that's why my images won't upload.
My JavaScript code in Twig:
<script>
var url = "{{ path('editor_file_upload') }}";
$(document).ready(function() {
$('.summernote').summernote({
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
function sendFile(file, editor, welEditable) {
let formData = new FormData();
formData.append("file", file);
$.ajax({
data: formData,
type: "POST",
url: url,
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
});
</script>
My Controller action:
/**
* #Route("/editor-file-upload", name="editor_file_upload")
*/
public function uploadEditorFile(Request $request)
{
/** #var UploadedFile $File */
$File = $request->files->get('file');
if ($File) {
$originalFilename = pathinfo($File->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename . '-' . uniqid() . '.' . $File->guessExtension();
try {
$File->move(
$this->getParameter('editor_images'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
}
}
The problem was that I didn't return any response, here's the edit:
/**
* #Route("/upload-editor", name="admin_upload_editor")
*/
public function uploadEditorFile(Request $request, KernelInterface $kernel) {
/** #var UploadedFile $file */
$file = $request->files->get('img');
if (empty($file))
{
return new Response("No file",Response::HTTP_UNPROCESSABLE_ENTITY, ['content-type' => 'text/plain']);
}
if ($file) {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename . '-' . uniqid() . '.' . $file->guessExtension();
try {
$file->move(
$kernel->getProjectDir() . '/' .
$this->getParameter('public_dir') . '/' .
$this->getParameter('editor_dir'),
$newFilename
);
return new Response("/editor_images/" . $newFilename, Response::HTTP_OK);
} catch (FileException $e) {
return new Response("Cannot upload file!",Response::HTTP_UNPROCESSABLE_ENTITY, ['content-type' => 'text/plain']);
}
}
}

Ajax response isn't showed on page

My ajax is
$.ajax({
type: 'POST',
url: ajax.ajax,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(msg){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
This is the PHP part
function form(){
global $wpdb;
$table = cars;
foreach ($_FILES as $file) {
if($file['error'] == UPLOAD_ERR_NO_FILE) {
continue;
}
$valid_ext = array( 'img' , 'png');
$extension_upload = strtolower( substr( strrchr($file['name'], '.') ,1) );
if ( in_array($extension_upload,$valid_ext) ) {
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$data = array( 'customer_resume' => $name_upload );
$format = array( '%s' );
$success=$wpdb->insert( $table, $data, $format );
$msg_true = 'Upload ok ';
} else {
$msg_error = 'Upload error';
}
}
$result = !isset($msg_error);
$msg = array();
if($result) {
$msg['error'] = 'true';
$msg['true'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['false'] = $msg_error;
}
header('Content-Type: application/json');
echo json_encode($msg);
}
And the HTML where I try to show the success or error message
<div id="error_message"></div>
<div id="success_message"></div>
When I click on Submit button I everything works fine and saved in database but there is no indication wheather is success or no. I've tried to add this msg's but still nothing shows on page.
PHP side:
You need to print same variable for success and failure:
if($result) {
$msg['error'] = 'true';
$msg['msg'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['msg'] = $msg_error;
}
JavaScript Side:
The AJAX response will come as
data.error -> true or false.
data.msg -> Success or Error message depending upon program logic.
...
success: function(data){
$('#success_message').fadeIn().html(data.msg);
...
What is hiding behind "ajax.ajax" ?
Also if you want to show your data you need to use "msg"
success: function(msg){
$('#success_message').fadeIn().html(msg);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}

Autocomplete implementation in cakephp 2.4

Hello Guys i am very new to cakephp and i want to implement autocomplete in my project. I have downloaded two javascript file jquery.autocomplete.js and jquery.autocomplete.min.js and placed them both in my webroot directory. i have a field named city in my database which i have to autocomplete. the problem is my sutocomple is not firing or even not showing alert when key is pressed.
my javascript code is
<script src="../../webroot/js/jquery.autocomplete.js"
type="text/javascript"></script>
<script src="../../webroot/js/jquery.autocomplete.min.js"
type="text/javascript"></script>
$(function() {
$('#Usercity').autocomplete({
alert("ashish");
//dataType: "json"
minLength: 1,
source: function( request, response ) {
$.ajax({
url: "/User/autoComplete",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
term: request.term
},
success: function( data ) {
response( $.map( data, function( el ) {
return { label: el.id, value: el.city }
}));
}
});
}
});
});
</script>
echo $this->Form-
>input('city',array('type'=>'text','label'=>'City'));
Controller code
public function autoComplete() {
Configure::write('debug', 0);
$this->layout = 'ajax';
$query = $_GET['term'];
$items = $this->User->find('all', array(
'conditions' => array('User.city LIKE' => $query . '%'),
'fields' => array('city')));
foreach ($items as $item) {
$data[] = $item['Item'];
}
$data = json_encode($data);
echo $data;
exit;
}
}
To fix problem
the problem is my sutocomple is not firing or even not showing alert
when key is pressed.
you need to load jQuery lib before autocomplete.js something like
<script src="../js/jquery-last.version.number.js"></script>
or if you want cakephp to do it for you (no need to write '.js')
echo $this->Html->script(array(
'jquery-1.10.2.min',
'jquery.autocomplete'
));

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

Categories

Resources