DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Selenium vs Cypress: Does Cypress Replace Selenium?
  • Creating a Secure REST API in Node.js
  • Cypress Web Automation
  • Open Source Tools Options in Web Application Development

Trending

  • How Clojure Shapes Teams and Products
  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  • Integrating Jenkins With Playwright TypeScript: A Complete Guide
  1. DZone
  2. Coding
  3. JavaScript
  4. Upload Files or Images to Server Using Node.js

Upload Files or Images to Server Using Node.js

In this post, we tackle the question of how to quickly and easily upload files to a server using Node.js, without writing a single line of server side code.

By 
Sibeesh Venu user avatar
Sibeesh Venu
·
Feb. 24, 17 · Tutorial
Likes (22)
Comment
Save
Tweet
Share
290.0K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will see how we can upload files or images to the server using Node.js. Here we are going to use Visual Studio for our development and the following NPM packages for our easy development:

  • Express
  • Multer
  • Body-parser
  • We will briefly explain the use of these packages. As you all know, Node.js is a runtime environment built on Chrome’s V8 JavaScript engine for server-side and networking application. And it is an open source which supports cross-platform. Node.js applications are written in pure JavaScript. If you are new to Node.js, I strongly recommend you read my previous posts about Node.js here.

    Download the Source Code for This Post

  • Upload Files Or Images To Server Using Node.js
  • Background

    A few years back, if you needed to upload any files or images to a server, you were completely dependent on server side languages like C# and PHP. Everything has changed after the Node.js revolution. Here I will show you how to upload the files to a server using Node.js, without writing even a single line of server-side code. Enjoy!

    Create a Blank Node.js Web Application

    Create a blank Node.js web application.

    new_node_js_web_application

    Set Up Dependencies in package.json

    To get started, we will set up our dependencies first. To do so, please open your package.json file and paste the preceding code.

     {
         "name": "node_js_file_upload",
         "version": "0.0.1",
         "description": "Node_JS_File_Upload",
         "main": "server.js",
         "dependencies": {
             "body-parser": "^1.15.2",
             "express": "^4.14.0",
             "multer": "^1.2.0"
         },
         "author": {
             "name": "Sibeesh"
         }
     }

    Now, run the NPM install command as follows.

     npm install 

    Once you run the command, you can see that the dependencies are installed in the solution.

    npm-Packages

    Now we can understand what are these dependencies used for.

    Express

    As per the Express Team, Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love. You can always learn more about Express Package here.

    Multer

    Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency. You can find out more about the multer package here.

    Start Using Our Dependencies

    You can create the instances of our dependencies as follows.

     var Express = require('express');
     var multer = require('multer');
     var bodyParser = require('body-parser');
     var app = Express();
     app.use(bodyParser.json());

    Then, it is time to create a storage which says where and how the files/images should be saved.

     var Storage = multer.diskStorage({
         destination: function(req, file, callback) {
             callback(null, "./Images");
         },
         filename: function(req, file, callback) {
             callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
         }
     });

    Each file contains the following information:

    fieldname: Field name specified in the form.
    originalname: Name of the file on the user’s computer.
    encoding: Encoding type of the file.
    mimetype: Mime type of the file.
    size: Size of the file in bytes.
    destination: The folder to which the file has been saved.
    filename: The name of the file in the destination.
    path: The full path to the uploaded file.
    buffer: A Buffer of the entire file.

    Now, create a multer object as follows.

     var upload = multer({
         storage: Storage
     }).array("imgUploader", 3); //Field name and max count

    Here, multer accepts the storage we created in our previous step as the parameter. The function

    array(fieldname[, maxCount])

    accepts an array of files, all with the name fieldname.

    Now it is time to write our post and get action.

     app.get("/", function(req, res) {
         res.sendFile(__dirname + "/index.html");
     });
     app.post("/api/Upload", function(req, res) {
         upload(req, res, function(err) {
             if (err) {
                 return res.end("Something went wrong!");
             }
             return res.end("File uploaded sucessfully!.");
         });
     });

    Here /api/Upload is the action name we are going to set in our HTML page which we will create soon. And last but not the least, we need to make sure that the app is listening to our particular port, in this case, it is port 2000.

     app.listen(2000, function(a) {
         console.log("Listening to port 2000");
     });

    Create an HTML Page and Set Up Uploading

    You can create the page as follows with the references of the jquery-3.1.1.min.js and jquery.form.min.js.

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
        <meta charset="utf-8" />
        <title>Upload images to server using Node JS</title>
        <script src="Scripts/jquery-3.1.1.min.js"></script>
        <script src="Scripts/jquery.form.min.js"></script>
    </head>
    
    <body>
        <form id="frmUploader" enctype="multipart/form-data" action="api/Upload/" method="post">
            <input type="file" name="imgUploader" multiple />
            <input type="submit" name="submit" id="btnSubmit" value="Upload" /> </form>
    </body>
    
    </html>

    Please be noted that the ecctype for your form must be multipart/form-data and the action must be same as we set in our API.

    Create an Ajax Submit Event

    Now it is time to create our ajax event where we are going to call our API.

    <script>
        $(document).ready(function() {
                    var options = {
                            beforeSubmit: showRequest, // pre-submit callback success: showResponse // post-submit callback }; // bind to the form's submit event $('#frmUploader').submit(function () { $(this).ajaxSubmit(options); // always return false to prevent standard browser submit and page navigation return false; }); }); // pre-submit callback function showRequest(formData, jqForm, options) { alert('Uploading is starting.'); return true; } // post-submit callback function showResponse(responseText, statusText, xhr, $form) { alert('status: ' + statusText + '\n\nresponseText: \n' + responseText ); }
    </script>

    ajaxSubmit function is part of the plugin jquery.form.min.js, so please make sure that you have included it.

    Run Your Application

    Now, run your application. Before running your application, you can always set your script file as your startup file, to set it, just right-click on your project and click on properties.

    set-start-up-file

    Now you can open your command prompt, and manually locate your project in the command prompt, or you can use the ‘Open command prompt here’ option. To select, right-click on your project and select the option as follows:

    open_command_prompt_here_option

    Now type nodeserver.js in your command prompt which will make sure that your server is running. And if everything is fine, you will see this: 

    node_server_js_output

    Our server is now ready, and we can run our web page! Now, go to your browser and type the URL as http://localhost:2000. Select few files using the file uploader we have created.

    select_fiels_in_file_upload

    If you click submit, you can see we are calling our method action and the files are uploaded.

    file_uploaded_successfully_

    solution_explorer_window_after_saving_files

    You can always download the source code attached to see the complete code and application. Happy coding!

    Node.js Upload mobile app Express Web application Dependency Command (computing) Open source

    Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

    Opinions expressed by DZone contributors are their own.

    Related

    • Selenium vs Cypress: Does Cypress Replace Selenium?
    • Creating a Secure REST API in Node.js
    • Cypress Web Automation
    • Open Source Tools Options in Web Application Development

    Partner Resources

    ×

    Comments
    Oops! Something Went Wrong

    The likes didn't load as expected. Please refresh the page and try again.

    ABOUT US

    • About DZone
    • Support and feedback
    • Community research
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Core Program
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 3343 Perimeter Hill Drive
    • Suite 100
    • Nashville, TN 37211
    • support@dzone.com

    Let's be friends:

    Likes
    There are no likes...yet! 👀
    Be the first to like this post!
    It looks like you're not logged in.
    Sign in to see who liked this post!