Skip to content

Instantly share code, notes, and snippets.

@RedactedProfile
Last active February 16, 2024 02:08
Show Gist options
  • Save RedactedProfile/ac48c270d2bbe739f9f3 to your computer and use it in GitHub Desktop.
Save RedactedProfile/ac48c270d2bbe739f9f3 to your computer and use it in GitHub Desktop.
CKEditor File Upload with Node and Express
var express = require('express');
var router = express.Router();
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
router.get('/', function(req, res) {
res.render('index');
});
router.post('/uploader', multipartMiddleware, function(req, res) {
var fs = require('fs');
fs.readFile(req.files.upload.path, function (err, data) {
var newPath = __dirname + '/../public/uploads/' + req.files.upload.name;
fs.writeFile(newPath, data, function (err) {
if (err) console.log({err: err});
else {
html = "";
html += "<script type='text/javascript'>";
html += " var funcNum = " + req.query.CKEditorFuncNum + ";";
html += " var url = \"/uploads/" + req.files.upload.name + "\";";
html += " var message = \"Uploaded file successfully\";";
html += "";
html += " window.parent.CKEDITOR.tools.callFunction(funcNum, url, message);";
html += "</script>";
res.send(html);
}
});
});
});
module.exports = router;
doctype html
body
form
textarea#ckeditor(name="content")
script.
CKEDITOR.replace('ckeditor', {
filebrowserUploadUrl: '/uploader'
});
@abirrugal
Copy link

abirrugal commented Nov 22, 2020

I always get an error not found (404) with folder uploader in two cases: set static path and not athough i create folder in root or in public folder. Why?

Use a dot(.) after +' sign. Like this: __dirname + './../public/uploads/' + req.files.upload.name;
It will save uploaded image to public/uploads So make a directory name uploads inside public directory first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment