I have a problem with uploading my images with ckeditor - javascript

I have tried to upload images with ckeditor but my problem is that the images upload to the server folders but ddoesnt show in my ckeditor text area , it show server response error , any help please ?
This is my code :
router.post('/upload&responseType=json', function(req, res) {
var fs = require('fs');
var tmpPath = req.files.upload.name;
l = tmpPath.split('/').length;`enter code here`
var fileName = tmpPath.split('/')[l - 1] + "_" + "s";
var buf = new Buffer.from(req.files["upload"].data);
var newPath ='public/uploads/'+tmpPath;
console.log(newPath);
console.log(tmpPath);
console.log(fileName);
fs.writeFile(newPath,buf, function (err) {
if (err) console.log({err: err});
else {
html = "uploaded";
html += "<script type='text/javascript'>";
html += " var funcNum = " + req.query.CKEditorFuncNum + ";";
html += " var url = \"/uploads/" + fileName;
html += " var message = \"Uploaded file successfully\";";
html += "";
html += " window.parent.CKEDITOR.tools.callFunction(funcNum, url, message);";
html += "</script>";
res.send(html);
}
});
});
This is my ckeditor
CKEDITOR.config.customConfig = '/js/ckeditor_config.js';
CKEDITOR.replace(editor2,{ filebrowserUploadUrl: '/upload', });
And this my ckeditor config file :
CKEDITOR.editorConfig = function( config )
{
config.filebrowserUploadMethod = 'form';
config.toolbar = 'MyToolbar';
config.toolbar_MyToolbar =
[
['Source','Templates'],
['Cut','Copy','Paste','SpellChecker','-','Scayt'],
['Undo','Redo','-','Find','Replace'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
['Maximize','-','About'],
'/',
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','SelectAll','RemoveFormat'],
['Link','Unlink','Anchor'],
['Styles','Format','Font','FontSize'],
['TextColor','BGColor']
];
};

You do not have to send the whole HTML in the newer versions of ckeditor..
You are just supposed to send the URL as shown below:
res.send({
url: "<SERVER_URL>/public/uploads/" + fileName,
})
If you are working on localhost
replace SERVER_URL with something like http://localhost:3000
Another thing, you have to set
app.use(express.static('public/uploads'));
If you want to access the image using the URL mentioned above.

Related

Javascript for loop returning same value

I have this JS function using which I'm using to upload files from HTML multi-file uploader to dropbox using Javascript SDK. It's working well. Now I'm trying to add list of file names that are failed to upload(when catch block executes) to a string named "failed", but it's adding the name of the first file for all the failed files. What am I doing wrong here?
function uploadFile() {
var count1=0,count2=0,loop=0, failed='';
const UPLOAD_FILE_SIZE_LIMIT = 150 * 1024 * 1024;
var ACCESS_TOKEN = 'SomeAccessToken';
var dbx = new Dropbox.Dropbox({
accessToken: ACCESS_TOKEN
});
var fileInput = document.getElementById('file-upload');
var formp= document.getElementById('formp');
for (var i = 0; i < fileInput.files.length; i++) {
formp.innerHTML='<p> Uploading ' + fileInput.files.length + ' files </p>' ;
var file = fileInput.files[i];
var filename = fileInput.files[i].name;
if (file.size < UPLOAD_FILE_SIZE_LIMIT) { // File is smaller than 150 Mb - use filesUpload API
dbx.filesUpload({path: '/Test/' + file.name, contents: file})
.then(function(response) {
var results = document.getElementById('results');
var br = document.createElement("br");
results.appendChild(document.createTextNode(file.name + 'File uploaded!'));
results.appendChild(br);
count1=count1+1;
if(count1+count2==fileInput.files.length)
{
formp.innerHTML='<p> Uploaded ' + count1 + ' files. Failed ' + count2 + ' files</p>';
}
console.log(response);
})
.catch(function(error) {
count2=count2+1;
console.error(error);
failed+=file.name;
if(count1+count2==fileInput.files.length)
{
formp.innerHTML='<p> Uploaded ' + count1 + ' files. Failed '+ count2 + ' files</p>';
}
});
}
}
As far as I have seen, I dint find anything wrong in this code. For testing purpose I commented few lines of your code and tested. The files names are properly concatenated to the "failed" string.
<form>
<input type="file" id="formp" multiple="true" accept="*/*" />
</form>
<pre></pre>
$('#formp').change(function (event) {
var count1=0,count2=0,loop=0, failed='';
const UPLOAD_FILE_SIZE_LIMIT = 150 * 1024 * 1024;
var ACCESS_TOKEN = 'SomeAccessToken';
/* var dbx = new Dropbox.Dropbox({
accessToken: ACCESS_TOKEN
}); */
var fileInput = document.getElementById('formp');
var formp= document.getElementById('formp');
for (var i = 0; i < fileInput.files.length; i++) {
formp.innerHTML='<p> Uploading ' + fileInput.files.length + ' files </p>' ;
var file = fileInput.files[i];
var filename = fileInput.files[i].name;
failed+=file.name;
console.log('Failed check', failed);
if (file.size < UPLOAD_FILE_SIZE_LIMIT) { // File is smaller than 150 Mb - use filesUpload API
// dbx.filesUpload({path: '/Test/' + file.name, contents: file})
// .then(function(response) {
// var results = document.getElementById('results');
// var br = document.createElement("br");
// results.appendChild(document.createTextNode(file.name + 'File uploaded!'));
// results.appendChild(br);
// count1=count1+1;
// if(count1+count2==fileInput.files.length)
// {
// formp.innerHTML='<p> Uploaded ' + count1 + ' files. Failed ' + count2 + ' files</p>';
// }
// console.log(response);
// })
// .catch(function(error) {
// count2=count2+1;
// console.error(error);
// failed+=file.name;
// if(count1+count2==fileInput.files.length)
// {
// formp.innerHTML='<p> Uploaded ' + count1 + ' files. Failed '+ count2 + ' files</p>';
// }
// });
}
}
});
Try the above code in jsFiddle.
There might be a chance that the first file name might be cached in file variable and might be displaying the same variable name for each and every loop again and again. So emptying the "file" variable at the end of the each loop might fix the issue.

Problems with Ajax on xampp

Hi i have a problem i was using usbwebserver for my localhost but i had to switch to xampp because of php 5.5. But now is one of my functions misbehaving. It shows only 2/6 pictures from directory and i don't know why. It's function that will add an image to my body when clicked on that image. No errors on page found.
var pom = document.getElementById("ImageAdd");
pom.style.visibility = "visible";
var dir = "uploads";
var fileextension = [".png", ".jpeg", ".jpg", ".gif"];
$.ajax({
url: dir,
success: function(data) {
for (var i = 0; i < fileextension.length; i++) {
$(data).find("a:contains(" + fileextension[i] + ")").each(function() {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("#ImageAdd").append("<img src=\"" + dir + filename + "\" onclick=\"addimg('" + dir + filename + "')\">");
});
}
}
});

Node.js Downloading multiples files asynchronously

In trying to get a hang of node.js asynchronous coding style, I decided to write a program that would read a text file containing a bunch of URLS to download and download each file. I started out writing a function to download just one file (which works fine), but having trouble extending the logic to download multiple files.
Here's the code:
var http = require("http"),
fs = require("fs"),
input = process.argv[2],
folder = "C:/Users/Wiz/Downloads/",
regex = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/,
urls = null,
url = "",
filename = "";
fs.readFile(input, "utf8", function(e, data) {
console.log("Reading file: " + input);
if (e) console.log("Got error:" + e.message);
urls = data.split("\n");
for (var i = urls.length; i--;) {
url = urls[i];
if (!url.match(regex)) continue;
filename = folder + url.substring(url.lastIndexOf('/') + 1);
downloadQueue.addItem(url, filename);
}
});
var downloadQueue = {
queue: [],
addItem: function(p_sSrc, p_sDest) {
this.queue.push({
src: p_sSrc,
dest: p_sDest
});
if (this.queue.length === 1) {
this.getNext();
}
},
getNext: function() {
var l_oItem = this.queue[0];
http.get(l_oItem.src, function(response) {
console.log("Downloading: " + l_oItem.dest);
var file = fs.createWriteStream(l_oItem.dest);
response.on("end", function() {
file.end();
console.log("Download complete.");
downloadQueue.removeItem();
}).on("error", function(error) {
console.log("Error: " + error.message);
fs.unlink(l_oItem.dest);
});
response.pipe(file);
});
},
removeItem: function() {
this.queue.splice(0, 1);
if (this.queue.length != 0) {
this.getNext();
} else {
console.log("All items downloaded");
}
}
};
How do I structure the code so that the completion of the first download can signal the initiation of the next one. Please note that this exercise is just for learning purposes, to understand how asynchronous coding works. In practice, I'm sure there are much better tools out there to download multiple files.
Try simple at first, it look like you copy paste codes and quite don't understand what they do.
Do a simple loop, that get the url, and print something.
var http = require('http');
URL = require('url').parse('http://www.timeapi.org/utc/now?format=%25F%20%25T%20-%20%25N')
URL['headers'] = {'User-Agent': 'Hello World'}
// launch 20 queries asynchronously
for(var i = 0; i < 20; i++) {
(function(i) {
console.log('Query ' + i + ' started');
var req = http.request(URL, function(res) {
console.log('Query ' + i + ' status: ' + res.statusCode + ' - ' + res.statusMessage);
res.on('data', function(content){
console.log('Query ' + i + ' ended - ' + content);
});
});
req.on('error', function(err) {
console.log('Query ' + i + ' return error: ' + err.message);
});
req.end();
})(i);
}
All the urls will be fetched asynchronously. You can observe that the response does not arrive in order, but are still processed correctly.
The difficulty with async is not to do the things is parallel, because you just write like a single task, and execute multiple time. It becomes complicated when you need for instance to wait for all tasks to finished before continuing. And for that, have a look at promises
Here is what I started out with. Figuring that each download was invoked asynchronously, they would all be independent of each other.
var http = require("http"),
fs = require("fs"),
input = process.argv[2],
folder = "C:/Users/Wiz/Downloads/",
regex = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/,
urls = null,
url = "",
filename = "";
fs.readFile(input, "utf8",
function(e, data) {
console.log("Reading file: " + input);
if (e) console.log("Got error:" + e.message);
urls = data.split("\n");
for (var i = urls.length; i--;) {
url = urls[i];
if (!url.match(regex)) continue;
filename = folder + url.substring(url.lastIndexOf('/') + 1);
http.get(url, function(response) {
var file = fs.createWriteStream(filename);
response.on("end", function() {
file.end();
});
response.pipe(file);
})
}
});

accessing a specific column in a csv file using javascript

My problem is simple. I would like to know if there is a way to access a specific column from a csv file which is in MS Excel format. There are about 40 fields or columns in the file. I want to access only 3 of these. Please guide me.
Thanks in advance
This is as far as I got. Can we count the number of columns in the file?
$(document).on("click","#bucket_list a",function(evt){
// console.log("ID :: ",evt.target.id);
var bucketID = evt.target.id;
evt.preventDefault();
// alert("Event Fired");
counter = 0;
//lists the bucket objects
s3Client.listObjects(params = {Bucket: bucketID}, function(err, data){
if (err) {
document.getElementById('status').innerHTML = 'Could not load objects from ' + bucketID;
} else {
//document.getElementById('status').innerHTML = 'Loaded ' + data.Contents.length + ' items from ' + bucketID;
var listStart = document.createElement("ul");
document.getElementById('status').appendChild(listStart);
for(var i=0; i<data.Contents.length;i++){
fileKey = data.Contents[i].Key;
if(fileKey.search(str) != -1) {
//var listItems = document.createElement("li");
//listItems.innerHTML = data.Contents[i].Key;
//listStart.appendChild(listItems);
fileList[i] = data.Contents[i].Key;
//alert(fileList[i]);
counter = counter + 1;
}
}
if(counter == 0){
alert("This bucket has no CSV files. Please try another bucket!");
}
// else{
// for(var i = 0; i<fileList.length;i++){
// alert("File: " + fileList[i]);
// }
// }
}
//to read the contents of the files into textviews
var file = fileList[0];
//console.log("Loading:: ", file);
s3Client.getObject(params={Bucket: bucketID, Key: file},function(err,data){
if(err != null){ alert("Failed to load object " + err); }
else{
//alert("Loaded " + data.ContentLength + " bytes");
var allDataLines = data.split(/\r\n|\n/);
var headers = allDataLines[0].split(',');
}
});
});
});
I am unable to figure out how to get only the second column.
Yes. You have to parse the csv file to get the values for a particular column.Refer the following post on how to read a CSV file in Javascript.
[How to read data From *.CSV file using javascript?
To give you a head start the logic is simple . You just have to split based on "," and do a if statement.

configuring to use localStorage as endpoint instead of local server

I am using a javascript library that generates annotations within an ePub. I am hoping to use HTML5 localStorage for storing the annotation data.
Is there a way to have an endpoint url associated with localStorage?
In the hook that invokes the library there is a variable for 'server', which is currently set to a url for the local server, port 5000.
I am hoping to replace that with some pointer to localStorage, but I'm not sure what endpoint would be involved. Seems like the only method for adding in information would be the method "localStorage.setItem", which in turn needs a variable name as an argument, so it wouldn't be appropriate as an endpoint.
The unadulterated hook, before I customized it is in this github repo,
My current version after editing, (which isn't functioning) is as follows:
EPUBJS.Hooks.register("beforeChapterDisplay").annotate = function(callback, chapter){
var chap = chapter.bodyEl,
server = localStorage;
files = [
EPUBJS.filePath + "annotator-full.js"
];
console.log(files);//show the pathways defined above
EPUBJS.core.load(files, chapter.doc.head);
$(chapter.doc.body).annotator().annotator('setupPlugins', {}, {
Filter:false,
Store: {
annotationData: {
'uri': chapter.path
},
loadFromSearch: {
'limit': 100,
'uri': chapter.path
}
}
});
Util.mousePosition = function(e, offsetEl) {
var offset;
offset = $(offsetEl).position();
return {
top: e.pageY,
left: e.pageX
};
};
devAnnotator = new Annotator(chapter.doc.body)
// .addPlugin('Auth', {
// tokenUrl: 'http://annotateit.org/api/token',//'http://localhost:5001/api/token'
// })
// .addPlugin('Unsupported')
// .addPlugin('AnnotateItPermissions')
// .addPlugin('Store', {
// prefix: 'http://annotateit.org/api',//'http://localhost:5000',
// loadFromSearch: {
// uri: chapter.currentChapter.href
// },
// annotationData: {
// uri: chapter.currentChapter.href
// }
// });
// devAnnotator.plugins.Auth.withToken(function (tok) {
// console.log(tok);
// })
// EPUBJS.core.addCss("../libs/annotator/css/annotator.css", false, chapter.doc.head);
if(callback) callback();
function annotate(){
// EPUBJS.core.addCss("css/annotator.css", false, chapter.doc.head);
var s = document.createElement("script");
s.type = 'text/javascript';
console.log(jQuery);
var a = "jQuery.migrateTrace = false;";
a += "console.log(document.getElementById('c001p0002').getBoundingClientRect());";
a += "var content = $('body').annotator().annotator('setupPlugins', {}, {Filter:false});";
//-- Use Local Server:
a += "var content = $('body').annotator(),";
a += " server = '" + server + "';";
a += " path = '" + chapter.path + "';";
a += " content.annotator('addPlugin', 'Store', {";
// The endpoint of the store on your server.
a += " prefix: server,";
// Attach the uri of the current page to all annotations to allow search.
a += " annotationData: {";
a += " 'uri': path";
a += " }";
// This will perform a search action rather than read when the plugin
// loads. Will request the last 20 annotations for the current url.
// eg. /store/endpoint/search?limit=20&uri=http://this/document/only
a += ","
a += " loadFromSearch: {";
a += " 'limit': 20,";
a += " 'uri': path";
a += " }";
a += "});";
s.innerHTML = a;
chapter.doc.body.appendChild(s);
if(callback) callback();
}
}
Just to close the loop on this, solution:
The file isn't an actual ePub, it is a "shell" for ingesting an ePub with ePub.js and then displaying it in a custom way...

Categories

Resources