Cloudinary Blog

Node.js File Upload to a Local Server Or to the Cloud

Node.js File Upload to a Local Server Or to the Cloud

Probably one of the best things to happen to JavaScript developers, Node.js empowers them to write and ship JavaScript on the back end. Thanks to Node.js, front-end developers can become full-stack developers in a snap.

The procedures below describe how to Node.js file upload's to your local server or to the cloud at Cloudinary.

Set Up a Node Project

First, download and install Node.js on your system. Afterwards, set up a Node.js back-end server with a package, such as Express. Do the following:

  1. Create an upload directory and run npm init there to generate a package.json file:

    Copy to clipboard
    npm init
  2. In the same directory, install Express:

    Copy to clipboard
    npm install express --save
  3. Create an index.js file with the code below:

    Copy to clipboard
    const express = require('express')
    const app = express()
    const port = 3000
    
    app.get('/', (req, res) => res.json({ message: 'Hello World!' }))
    
    app.listen(port, () => console.log(`This is the beginning of the Node File Upload App`))
  4. Run the project with the command node index.js.

    Your back-end server is now up and running.

    upload

    Afterwards, multer creates an images directory in which to display the details of the recently uploaded file in your console. See this example:

    node upload

    For simultaneous multiple file uploads, just change fileUpload.single to fileUpload.array:

Copy to clipboard
...
app.post('/photos/upload', fileUpload.array('image', 5), function (req, res, next) {
      console.log("Images ", req.file);  
})

5 above can be any numeric value, denoting the number of files you plan to upload.

Step 2: Set up file uploads to Cloudinary

Completing step 1 enables you to upload files to your local server. For multiple files, best store them in a central location like Cloudinary and behind a content delivery network (CDN) at scale for efficient retrieval and delivery to users.

This step establishes the mechanics for uploading files to Cloudinary.

As a prerequisite, sign up for a free account on Cloudinary. Note your cloud name and API keys on the dashboard.

media library

Now do the following.

  1. Rewrite multer to accept zero arguments:

    Copy to clipboard
    const fileUpload = multer()

    Instead of being written to a local directory, the uploaded files now reside in memory temporarily as a buffer.

  2. Install Cloudinary’s Node.js SDK and the streamifier library:

    Copy to clipboard
    npm install cloudinary 
    npm install streamifier
  3. Make the cloudinary and streamifier required libraries in your codebase:

    Copy to clipboard
    ...
    const cloudinary = require('cloudinary').v2
    const streamifier = require('streamifier')
    ...
  4. Rewrite the /upload endpoint code to upload files to Cloudinary:

    Copy to clipboard
    app.post('/upload', fileUpload.single('image'), function (req, res, next) {
    let streamUpload = (req) => {
        return new Promise((resolve, reject) => {
            let stream = cloudinary.uploader.upload_stream(
              (error, result) => {
                if (result) {
                  resolve(result);
                } else {
                  reject(error);
                }
              }
            );
    
           streamifier.createReadStream(req.file.buffer).pipe(stream);
        });
    };
    
    async function upload(req) {
        let result = await streamUpload(req);
        console.log(result);
    }
    
    upload(req);
    });

Recall that you rewrote multer earlier to process and store uploaded files temporarily as a buffer. streamifier now converts the uploaded buffer to a readable stream, after which Cloudinary’s upload_stream method streams directly to the cloud.

The returned result looks like this, complete with the details on the recently uploaded file:

node.js index

Now you can fetch the URL from the JSON response and store it in the database. Mission accomplished.

A Word About Cloudinary’s Node.js SDK

Besides uploading images and videos, Cloudinary’s Node.js SDK can also transform, optimizatize, and deliver them. You can seamlessly integrate those capabilities with your Node.js app. For details, see the related documentation.

Want to Learn More About File Uploads?

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more