Upload Files Or Images To Server Using Node.js

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 preceding NPM packages for easy development.

  • Express
  • Multer
  • Body-parser

We will briefly explain the use of these packages. As you all know, Node.js is a run time environment built on Chrome’s V8 JavaScript engine for the server side and networking applications. It is open source, which supports cross platforms. 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 source code

Background

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

Create a Blank Node.jsWeb Application

Create a blank Node.jsWeb Application.

new_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.

  1. {  
  2. "name""node_js_file_upload",  
  3. "version""0.0.1",  
  4. "description""Node_JS_File_Upload",  
  5. "main""server.js",  
  6. "dependencies": {  
  7. "body-parser""^1.15.2",  
  8. "express""^4.14.0",  
  9. "multer""^1.2.0"  
  10. },  
  11. "author": {  
  12. "name""Sibeesh"  
  13. }  
  14. }  
Now, run NPM install command, as shown below.
  1. npm install  
Once you run the command, you can see that the dependencies are installed in the solution.

npm-packages

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 the Web and mobile applications. Express provides a thin layer of the fundamental web application features without obscuring Node.js features that you know and love. You can always learn more about Express packages.

  • 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. Please read more about multer package.

Start using our dependencies

You can create the instances of our dependencies, as shown below.

  1. var Express = require('express');  
  2. var multer = require('multer');  
  3. var bodyParser = require('body-parser');  
  4. var app = Express();  
  5. app.use(bodyParser.json());  
It is the time to create a storage, which says where and how the files/images should be saved.
  1. var Storage = multer.diskStorage({  
  2.     destination: function(req, file, callback) {  
  3.         callback(null"./Images");  
  4.     },  
  5.     filename: function(req, file, callback) {  
  6.         callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);  
  7.     }  
  8. });  
Each file contains the information given below..
  • 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 within the destination.
  • path : The full path to the uploaded file.
  • buffer : A buffer of the entire file.

Now, please create multer object, as shown below.

  1. var upload = multer({ storage: Storage }).array("imgUploader", 3); //Field name and max count  
Here, multer  accepts the storage that we created in our previous step as the parameter. The function is given below.
  1. array(fieldname[, maxCount])  
Accept an array of the files, all with the name fieldname.

Now, it is the time to write our POST and GET action.

  1. app.get("/"function(req, res) {  
  2.     res.sendFile(__dirname + "/index.html");  
  3. });  
  4. app.post("/api/Upload"function(req, res) {  
  5.     upload(req, res, function(err) {  
  6.         if (err) {  
  7.             return res.end("Something went wrong!");  
  8.         }  
  9.         return res.end("File uploaded sucessfully!.");  
  10.     });  
  11. });  
Here /api/Upload is the action name, which we are going to set in out HTML page, which we will create soon. Last but not least, we need to make sure that the app is listening to our particular port. In this case; it is port 2000.
  1. app.listen(2000, function(a)  
  2. {  
  3.     console.log("Listening to port 2000");  
  4. });  
Create HTML page and set up uploading 

You can create the page, as shown below, with the references of the jQuery-3.1.1.min.js and jQuery.form.min.js.

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <title>Upload images to server using Node JS</title>  
  7.     <script src="Scripts/jquery-3.1.1.min.js"></script>  
  8.     <script src="Scripts/jquery.form.min.js"></script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <form id="frmUploader" enctype="multipart/form-data" action="api/Upload/" method="post">  
  13.         <input type="file" name="imgUploader" multiple />  
  14.         <input type="submit" name="submit" id="btnSubmit" value="Upload" />  
  15.     </form>  
  16. </body>  
  17.   
  18. </html>  
Please note that the ecctype for your form must be multipart/form-data and the action must be same as we set in our API.

Create AJAX submit event

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

  1. <script>  
  2.     $(document).ready(function() {  
  3.         var options = {  
  4.             beforeSubmit: showRequest, // pre-submit callback  
  5.             success: showResponse // post-submit callback  
  6.         };  
  7.         // bind to the form's submit event  
  8.         $('#frmUploader').submit(function() {  
  9.             $(this).ajaxSubmit(options);  
  10.             // always return false to prevent standard browser submit and page navigation  
  11.             return false;  
  12.         });  
  13.     });  
  14.     // pre-submit callback  
  15.     function showRequest(formData, jqForm, options) {  
  16.         alert('Uploading is starting.');  
  17.         return true;  
  18.     }  
  19.     // post-submit callback  
  20.     function showResponse(responseText, statusText, xhr, $form) {  
  21.         alert('status: ' + statusText + '\n\nresponseText: \n' + responseText);  
  22.     }  
  23. </script>  
ajaxSubmit function is a part of the plugin jQuery.form.min.js, so please make sure that you have included it.

Run your Application

Now, please run your Application. Before running your Application, you can always set your script file as your start up file. To set it, please right click on your project and click properties.

set-start-up-file

set-start-up-file

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

open_command_prompt_here_option

open_command_prompt_here_option

Now, type node Server.js in your command prompt, which will make sure that your Server is running. If everything is fine, you can see a Window, as shown below.

node_server_js_output

node_server_js_output

We can run our Webpage now as our Server is ready. Please go to your Browser and type the URL as http://localhost:2000. Select a few files, using the file uploader, which we have created.

select_fiels_in_file_upload

select_fiels_in_file_upload

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

file_uploaded_successfully_
file_uploaded_successfully_

solution_explorer_window_after_saving_files

solution_explorer_window_after_saving_files

You can always download the source code attached to see the complete code and an Application. Happy coding..

See also

Conclusion

Did I miss anything that you may think is required? Have you found this post useful? I hope you liked this article. Please share your valuable suggestions and feedback with me.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, ASP.NET Forum instead of commenting here. Tweet or E-mail me a link of your question there and I’ll definitely try to help if I can.

Please see this article in my blog here.


Similar Articles