Node.JS

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.

Dependencies

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

Frontend

The main index page.

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

  <!-- Include external CSS. -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.0/codemirror.min.css">

  <!-- Include Editor style. -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.5.1/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.5.1/css/froala_style.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <!-- Include external JS libs. -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.0/codemirror.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.0/mode/xml/xml.min.js"></script>

  <!-- Include Editor JS files. -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.5.1//js/froala_editor.pkgd.min.js"></script>
  <div class="sample">
    <h2>File upload example.</h2>
    <form>
      <textarea id="edit" name="content"></textarea>
    </form>
  </div>

  <!-- Initialize the editor. -->
   <script>
     $(function() {
      $('#edit').froalaEditor({
        // Set the file upload URL.
        imageUploadURL: 'image_upload',
        imageUploadParams: {
          id: 'my_editor'
        }
      })
    });
  </script>
</body>
</html>

Backend

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.
app.post("/file_upload", function (req, res) {
  upload_file(req, function(err, data) {

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

    res.send(data);
  });
});

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

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

    res.send(data);
  });
});

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

if (!fs.existsSync(filesDir)){
  fs.mkdirSync(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) {
     return;
    }

    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.
      file.resume();
      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.
    file.pipe(diskWriterStream);
  });

  // 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;