How to upload files to the server using JavaScript
Tags: javascript, json
Published: 2023-06-14 11:23:39


---
title: How to upload files to the server using JavaScript
published: true
description:  Learning how to upload files to the server using JavaScript
date: 2023-14-06 11:21 UTC
tags: javascript, json
canonical_url: https://www.ma-no.org/en/programming/javascript/how-to-upload-files-to-the-server-using-javascript
cover_image: https://www.ma-no.org/cache/galleries/contents-2303/960-400/how-to-upload-files-to-the-server-using-javascript-imppng.webp
# Use a ratio of 100:42 for best results.
# published_at:  2023-14-06 11:21 UTC +0000
---



<p>In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to upload an avatar, a thumbnail, a PDF file or any other image or file in various formats.</p>
<p>We are going to structure this tutorial in several parts. First we will create the project, then we will create the frontend code and finally the backend code for the server.</p>
<p>To understand this tutorial you will need some basic knowledge of the command line. If you have never used the command line before, see the following command line tutorial, which explains some basic commands for the most commonly used operating systems. You will also need to have both Node.js and the npm package manager installed. </p>
<br>
### Creating the project
<p>The first thing we are going to do is to configure and create the project. To do this, create an empty directory somewhere, access it via the command line and use the following command to create the project:</p>
<br><pre>npm init</pre><br>
<p>We only need to install two packages. First install express using the following command:</p>
<br><pre>npm install express</pre><br>
<p>Next we will also need a middleware for express called express-fileupload which we can use to manage the files that are sent to the server:</p>
<br><pre>npm install express-fileupload</pre><br>
<p>Next, configure the file that will create the express server. To do this, edit the package.json file, which should contain the line &quot;start&quot;: &quot;node index.js&quot; in the scripts section to tell Node which file to run when we start the application:</p>
<br><pre>{    
"name": "ulpload-file-ajax",    
"description": "Tutorial in which an ajax medium file is created",    
"version": "1.0.0",    
"dependencies": {      
  "express": "4.16.2",      
  "express-fileupload": "^1.1.7-alpha.3",      
  "request": "^2.88.2"    
},    
"scripts": {     
  "start": "node index.js"    
 }  
}</pre><br>
<p>Next, we create the index.js file in the root folder of the project and we add the necessary code for the creation of a basic server:</p>
<br><pre>
const express = require('express');
const router = express.Router();

const bodyParser = require('body-parser');
const fileupload = require('express-fileupload');
const FileController = require('./controllers/FileController');

const app = express();
const fileController = new FileController();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileupload());

router.post('/ulpload-file', fileController.uploadFile);

router.use(function(req, res) {
   res.status(404).json({
     error: true,
     message: 'Not Found'
   });
});

app.use('/api', router);

app.use(express.static(__dirname));
app.get('/', function (req, res) {
   res.render('index.html');
});

var port = 3000;
app.listen(port, function () {
   console.log('Server', process.pid, 'listening on port', port);
});

module.exports = app;
</pre><br>
<p>What we have done is to create the server. At the top of the file we have made a require of the <code>express-fileupload</code> module, which is essential for uploading files.</p>
<p>We have included the <code>FileController</code> class, located in the <code>/controllers/FileController.js</code> file, although we haven't created it yet. In the <code>uploadFile</code> function of this controller is where we will add the code in charge of uploading the file.</p>
<p>As for the path that will redirect the request to the controller, we have defined the path <code>/api/upload-file</code> using the following function:</p>
<br><pre>router.post('/upload-file', fileController.uploadFile);</pre><br>
<p>We have added the <code>/api</code> prefix to the path using the following statement:</p>
<br><pre>app.use('/api', router);</pre><br>
<p>Please have a look at this file, as we will be creating the frontend code next.</p>
<br>
### 2. Frontend JavaScript code</h3><br>
<p>In this section we will add the frontend code in charge of sending the file from the user's system to the server. To start, create the <code>index.html</code> file in the root folder of the project. Next, edit the file you just created and copy and paste the following code, which we will explain later:</p>
<br><pre>&lt;!DOCTYPE html&gt;  
&lt;html lang="es"&gt;    
 &lt;head&gt;      
   &lt;meta charset="utf-8" /&gt;      
   &lt;meta http-equiv="x-ua-compatible" content="ie=edge" /&gt;      
   &lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt;      
   &lt;title&gt;Ajax Node File Upload Tutorial&lt;/title&gt;    
 &lt;/head&gt;    
 &lt;body&gt;        
   &lt;h1&gt;Ajax Node File Upload Tutorial&lt;/h1&gt;      
   &lt;p&gt;&lt;label&gt;Select a new file!&lt;/label&gt;&lt;/p&gt;      
   &lt;input type="file" id="upload_file" /&gt;      
   &lt;div id="result"&gt;&lt;/div&gt;      
   &lt;script type="text/javascript" src="resources/js/scripts.js"&gt;&lt;/script&gt;    
 &lt;/body&gt;  
&lt;/html&gt;</pre><br>
<p>What we have done is to add a basic HTML5 template. We have also added an HTML <code>input</code> field, which is the field that the user will interact with to upload the file:</p>
<br>
<pre>&lt;input type="file" id="upload_file" /&gt;</pre>
<br>
<p>As you can see, we've linked to the <code>/resources/js/scripts.js </code> script just before the closing <code>&lt;/body&gt;</code> tag. Let's add it, so first create the <code>/resources/js</code> directory and then create and edit the <code>scripts.js</code> file.</p>
<p>Now we are going to add the JavaScript code that will allow us to associate an event to the field we have created in order to upload the file to the server. First we will see the code and then we will explain it:</p>
<br><pre>
const uploadImage= event =&gt; {
 const files = event.target.files;
 const data = new FormData();
 data.append('file', files[0]);
 fetch('/api/upload-file', {
    method: 'POST',
    body: data
 })
 .then(response =&gt; response.json())
 .then(data =&gt; {
   document.getElementById('result').innerHTML = 'The file ' + data.path + ' has been successfully uploaded.';
 })
 .catch(error =&gt; {
    console.error(error);
 });
}
document.querySelector('#upload_file').addEventListener('change', event =&gt; {
   uploadImage(event);
});</pre><br>
<p>
In the last block of code we have registered a <code>change</code> event for the input we use to upload the file. In this event we execute the function <code>uploadImage</code>, which receives as parameter the click event itself, from where we will have access to the selected file.</p>

<p>What we do in the <code>uploadImage</code> function is to get the selected file, located in the <code>event.target.files</code> array. Then we create a <code>FormData</code> object and assign the selected file to it. Finally we use the fetch function to send a <code>POST</code> request to the <code>/api/upload-file</code> path we created on the server. </p>
<p>Then we check if the file upload has been completed successfully, printing in the <code>result</code> field the file path if it has been uploaded correctly, or displaying an error in the console otherwise. We return the path in the <code>path</code> property.</p>
### 3. Node.js Backend Code<br>
<p>Now let's take a look at the process that is followed on the server to upload the file. The first thing you need to do is create the <code>/uploads</code> directory in the root folder of your project. This is the directory where we will upload the files.</p>
<p>We're going to create the <code>/controllers/FileController.js</code> file as a controller. As before, we'll first look at the code for this file and then explain how it works:</p>
<br><pre>class FileController
{
  uploadFile = async (req, res, next) =&gt;
  {
   const file = req.files.file;
   const fileName = file.name;
   const path = __dirname + '/../uploads/' + fileName;
   
   try {
    file.mv(path, (error) =&gt; {
     if (error) {
     console.error(error);
     res.writeHead(500, {
       'Content-Type': 'application/json'
  });
   res.end(JSON.stringify({ status: 'error', message: error }));
     return;
   }
   return res.status(200).send({ status: 'success', path:'/uploads/' + fileName });
  });
  } catch (e) {
   res.status(500).json({
    error: true,
    message: e.toString()
   });
  }
 }
}

module.exports = FileController;
</pre><br>
<p>We have created a class called <code>FileController</code> as a controller, in which we have defined the <code>uploadFile</code> function.</p>
<p>The first thing we do is to get the file we have sent, which should be in the variable <code>req.files.file</code>, since <code>file</code> was the name we have given it in the frontend code. Now we can get the name of the file, which will be in the variable <code>file.name</code>.</p>
<p>Next, we have defined the <code>path</code> where we are going to copy the file and then, using the function <code>file.mv</code>, we copy the file to that path.</p>
<p>In case the file has been copied successfully, we will send the response back in JSON format:</p>
<br><pre>return res.status(200).send({ status: 'success', path:'/uploads/' + fileName });</pre><br>
<p>Otherwise, an error is returned.</p>
### 4. Testing the app<br>
<p>Let's test the application to verify that everything works correctly. To do this, open a terminal window and go to the root folder of the project. Then run the following command to start the server:</p>
<br><pre>npm start</pre><br>
Then go to the URL <code>http://localhost:3000/</code> and try uploading a file, such as an image in <code>.png</code> or <code>.jpg</code> format.
<p>And that is all.</p>