Froala Editor v4.2.1 is HereLEARN MORE

Skip to content


Image Upload

The following code example illustrates how to handle image upload on your server using Node.JS as a server-side language. For step by step explanation of the upload flow see image upload concept.


The node.JS image upload example needs the following dependencies:

Make sure that you run npm install, or if you are using bower run bower install


The main index page.

<!DOCTYPE html>
  <meta charset="utf-8">

  <!-- Include external CSS. -->
  <link href="" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" href="">

  <!-- Include Editor style. -->
  <link href="[email protected]/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
  <link href="[email protected]/css/froala_style.min.css" rel="stylesheet" type="text/css" />

  <!-- Include external JS libs. -->
  <script type="text/javascript" src=""></script>
  <script type="text/javascript" src=""></script>
  <script type="text/javascript" src=""></script>

  <!-- Include Editor JS files. -->
  <script type="text/javascript" src="[email protected]//js/froala_editor.pkgd.min.js"></script>
  <div class="sample">
    <h2>File upload example.</h2>
      <textarea id="edit" name="content"></textarea>

  <!-- Initialize the editor. -->
     $(function() {
        // Set the file upload URL.
        imageUploadURL: 'image_upload',
        imageUploadParams: {
          id: 'my_editor'


server.js file will handle the server part for Node.JS

The server.js file will be a handle for both image and file upload

// Include required libs
var express = require("express");
var app = express();
var bodyParser = require("body-parser")
var path = require("path");
var fs = require("fs");
var upload_file = require("./file_upload.js");
var upload_image = require("./image_upload.js");

app.use(express.static(__dirname + "/"));
app.use(bodyParser.urlencoded({ extended: false }));

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");

// File POST handler."/file_upload", function (req, res) {
  upload_file(req, function(err, data) {

    if (err) {
      return res.status(404).end(JSON.stringify(err));


// Image POST handler."/image_upload", function (req, res) {
  upload_image(req, function(err, data) {

    if (err) {
      return res.status(404).end(JSON.stringify(err));


// Create folder for uploading files.
var filesDir = path.join(path.dirname(require.main.filename), "uploads");

if (!fs.existsSync(filesDir)){

// Init server.
app.listen(3000, function () {
  console.log("Example app listening on port 3000!");

image_upload.js file will do the upload part. It has basic image format validations this can be easily extended.

The uploads directory must be set to a valid location before any uploads are made. The path can be any folder that is accessible and write available.

After processing the uploaded image, if it passes the validation, the server will respond with a JSON object containing a link to the uploaded file.

E.g.: {"link":"http://server_address/uploads/name_of_file"}

var Busboy = require("busboy");
var path = require("path");
var fs = require("fs");
var sha1 = require("sha1");

// Gets a filename extension.
function getExtension(filename) {
  return filename.split(".").pop();

// Test if a image is valid based on its extension and mime type.
function isImageValid(filename, mimetype) {
  var allowedExts = ["gif", "jpeg", "jpg", "png", "svg", "blob"];
  var allowedMimeTypes = ["image/gif", "image/jpeg", "image/pjpeg", "image/x-png", "image/png", "image/svg+xml"];

  // Get image extension.
  var extension = getExtension(filename);

  return allowedExts.indexOf(extension.toLowerCase()) != -1  &&
     allowedMimeTypes.indexOf(mimetype) != -1;

function upload (req, callback) {
  // The route on which the image is saved.
  var fileRoute = "/uploads/";

  // Server side file path on which the image is saved.
  var saveToPath = null;

  // Flag to tell if a stream had an error.
  var hadStreamError = null;

  // Used for sending response.
  var link = null;

  // Stream error handler.
  function handleStreamError(error) {
    // Do not enter twice in here.
    if (hadStreamError) {

    hadStreamError = error;

    // Cleanup: delete the saved path.
    if (saveToPath) {
     return fs.unlink(saveToPath, function (err) {
       return callback(error);

    return callback(error);

  // Instantiate Busboy.
  try {
    var busboy = new Busboy({ headers: req.headers });
  } catch(e) {
    return callback(e);

  // Handle file arrival.
  busboy.on("file", function(fieldname, file, filename, encoding, mimetype) {
    // Check fieldname:
    if ("file" != fieldname) {
      // Stop receiving from this stream.
      return callback("Fieldname is not correct. It must be "file".");

    // Generate link.
    var randomName = sha1(new Date().getTime()) + "." + getExtension(filename);
    link = fileRoute + randomName;

    // Generate path where the file will be saved.
    var appDir = path.dirname(require.main.filename);
    saveToPath = path.join(appDir, link);

    // Pipe reader stream (file from client) into writer stream (file from disk).
    file.on("error", handleStreamError);

    // Create stream writer to save to file to disk.
    var diskWriterStream = fs.createWriteStream(saveToPath);
    diskWriterStream.on("error", handleStreamError);

    // Validate image after it is successfully saved to disk.
    diskWriterStream.on("finish", function() {
     // Check if image is valid
     var status = isImageValid(saveToPath, mimetype);

     if (!status) {
       return handleStreamError("File does not meet the validation.");

     return callback(null, {link: link});

    // Save image to disk.

  // Handle file upload termination.
  busboy.on("error", handleStreamError);
  req.on("error", handleStreamError);

  // Pipe reader stream into writer stream.
  return req.pipe(busboy);

module.exports = upload;