Summernote upload not working - javascript

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

Related

Cloud Convert job error "started too many jobs at once"

I'm sending files to a php script from an html form. In the php script, I'm getting the temp file location and trying to convert it from a jpg to png. I'm getting this error from the server when trying to convert the file:
CloudConvert\Exceptions\HttpClientException: You have started too many
jobs at once in
C:\xampp\htdocs\photocloud\vendor\cloudconvert\cloudconvert-php\src\Exceptions\HttpClientException
upload.php:
require 'vendor/autoload.php';
use \CloudConvert\CloudConvert;
use \CloudConvert\Models\Job;
use \CloudConvert\Models\ImportUploadTask;
use \CloudConvert\Models\Task;
$obj_temp = $_FILES['file']['tmp_name'];
$obj_name = $_FILES['file']['name'];
$obj_errors = $_FILES['file']['error'];
$obj_checksum = md5_file($obj_temp, false);
$obj_size = filesize($obj_temp);
$obj_extention = strtolower(pathinfo($obj_name, PATHINFO_EXTENSION));
$cloudconvert = new CloudConvert([
'api_key' => 'my_key_here',
'sandbox' => false
]);
$obj_key = $obj_checksum.'.'.$obj_extention;
$job = (new Job())
->addTask(new Task('import/upload','upload-my-file'))
->addTask(
(new Task('convert', 'convert-my-file'))
->set('input', 'upload-my-file')
->set('output_format', 'png')
)
->addTask(
(new Task('export/url', 'export-my-file'))
->set('input', 'convert-my-file')
);
$cloudconvert->jobs()->create($job);
$url_task = $job->getTasks()->whereName('export-my-file')[0];
$cloudconvert->tasks()->upload($url_task, fopen($obj_temp, 'r'), 'test.png');
$cloudconvert->jobs()->wait($job);
foreach ($job->getExportUrls() as $file) {
echo $file->url;
}
upload.js
var fileInput = document.querySelector('.upload');
$.each(fileInput.files, function(index, val) {
formData = new FormData();
formData.append('file', fileInput.files[index]);
$.ajax({
type: 'POST',
url: 'upload.php',
processData: false,
contentType: false,
data: formData,
success: function(response) {
console.log(response);
}
});
});

JavaScript formdata multiple upload

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.

summernote js upload image

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');

Ajax method working twice in a button click

The file upload function working on the Upload button click.The function
$("#fuPDFAdd").change(function () {})
file upload change is working two time when click the 'btnUploadAdd' button.
How can avoid this
<div id="divUploadFileAdd">
<form enctype="multipart/form-data" id="frmUplaodFileAdd">
#Html.AntiForgeryToken()
<input id="fuPDFAdd" name="file" type="file" style = "display:none;"/>
<button class="" id="btnUploadAdd" type="button" onclick="test()">Upload</button>
<label id="txtuploadedMsgAdd"> </label>
</form>
</div>
$(document).ready(function () {
$("#fuPDFAdd").change(function () {
console.log("tst1");
var file = this.files[0];
fileName = file.name;
size = file.size;
type = file.type;
if (type.toLowerCase() == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { //I just want pdf files and only want to show
var formData = new FormData($('#frmUplaodFileAdd')[0]);
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
grdStaffAddition.PerformCallback({ transStatus: "New" });
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'success', 'Template migration completed' + data.result, 'CAM - Contract Staff');
}
});
}
else {
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'error', 'Please select xls/xlsx file.', 'CAM - Contract Staff');
}
});
});
function test() {
$("#fuPDFAdd").click();
}
Something like this will work, I did wrap the file upload code to a separate function there, and make it to call this new function from your event listeners.
function uploadTheFile() {
console.log("tst1");
var file = this.files[0];
fileName = file.name;
size = file.size;
type = file.type;
if (type.toLowerCase() == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { //I just want pdf files and only want to show
var formData = new FormData($('#frmUplaodFileAdd')[0]);
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function(data) {
grdStaffAddition.PerformCallback({
transStatus: "New"
});
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'success', 'Template migration completed' + data.result, 'CAM - Contract Staff');
}
});
} else {
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'error', 'Please select xls/xlsx file.', 'CAM - Contract Staff');
}
}
$("#fuPDFAdd").change(function() {
uploadTheFile();
});
function test() {
uploadTheFile();
}

Send Cropped image to database ajax On client and PHP on server

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 () {}
});
});

Categories