Node js Express Upload File/Image Example

Node js Express Upload File/Image Example

Node js Express Upload File/Image Example. In this tutorial, you have learned how to upload files and images in node js express framework.

Overview

In this node js files/image upload tutorial, you will learn how to upload files/image in node js express framework using busboy package.

File upload is the basic requirement of any application. Here we will demonstrate how to upload files in node js express framework.

So let’s get started with the file upload in node js express

We are using node js express framework and busboy to handle the form, you can use any other framework as per your requirement

Dependencies

  • express
  • busboy

    First install dependencies

Run the below command to install the dependencies

npm install express

npm install busboy

Export Dependencies

var express = require('express'),
var Busboy = require('busboy')

Create Form

To upload a file we need a form. We will create a form with a file input element that allows us to choose the file and a button to submit the form.

 app.get('/', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
})

Make sure your form must have enctype="multipart/form-data"attribute and form method should be post

Handle Form Submit

Here we will handle the form, We will parse the form and store the file in the folder. To send the file in the server we must have the post method in the form. We will create a route with the post method

app.post('/fileupload', function (req, res) {
    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {

      var saveTo = path.join(__dirname, 'uploads/' + filename);
      file.pipe(fs.createWriteStream(saveTo));
    });

    busboy.on('finish', function() {
      res.writeHead(200, { 'Connection': 'close' });
      res.end("That's all folks!");
    });

    return req.pipe(busboy);   
});

After completing the above steps your file will look like this

var http = require('http'),
    express = require('express'),
    Busboy = require('busboy'),
    path = require('path'),
    fs = require('fs');

var app = express();

app.get('/', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
})

app.post('/fileupload', function (req, res) {
    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {

      var saveTo = path.join(__dirname, 'uploads/' + filename);
      file.pipe(fs.createWriteStream(saveTo));
    });

    busboy.on('finish', function() {
      res.writeHead(200, { 'Connection': 'close' });
      res.end("That's all folks!");
    });

    return req.pipe(busboy);   
});

app.listen(8080);

Click to know more about the express

See the preview of node js file upload:

Further reading:

Async vs. Sync Handling Concurrency in JS

4 Ways to Empty an Array in Node.js

How to programmatically compress PNG images using Node.js

MongoDB Nodejs Tutorial with Examples

Renaming files using Node.js

Dockerizing a Node.js web application

Testing Node API with Mocha & Chai

Performing Sentiment Analysis on Tweets from Node.js

node-js javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.