In this tutorial, we’re gonna create Node.js Express example that provides Rest API to download file to Client from url (on server).
This Node.js server works with:
– Angular 8 Client / Angular 10 Client / Angular 11 Client / Angular 12
– Vue Client / Vuetify Client
– React Client / React Hooks Client
– React Material UI Client
Related Posts:
– Node.js Express File Upload Rest API example
– Node.js Rest APIs example with Express, Sequelize & MySQL
Contents
Node.js Express Download File overview
Our Node.js Application will provide APIs for:
- getting list of Files’ information (file name & url)
- downloading File from server with the link
This is the static folder that stores all files:
If we get list of files, the Node.js Rest Apis will return:
Each item in the response array has a url that you can use for downloading the file.
These are APIs to be exported:
Methods | Urls | Actions |
---|---|---|
POST | /upload | upload a File |
GET | /files | get List of Files (name & url) |
GET | /files/[filename] | download a File |
The source code at the end of this post will cover all of these APIs. But this tutorial only shows you how to get list of files’ info and download the file from server with url.
You can visit following tutorial for uploading files to the static folder:
Node.js Express File Upload Rest API example
Technology
- express 4.17.1
- cors 2.8.5
Project Structure
This is the project directory that we’re gonna build:
– resources/static/assets/uploads
: folder for storing files to download.
– file.controller.js
exports functions to get files’ information and download a File with url.
– routes/index.js
: defines routes for endpoints that is called from HTTP Client, use controller to handle requests.
– server.js
: initializes routes, runs Express app.
Setup Node.js Express File Upload project
Open command prompt, change current directory to the root folder of our project.
Install Express, CORS modules with the following command:
npm install express cors
The package.json file will look like this:
{
"name": "node-js-express-download-files",
"version": "1.0.0",
"description": "Node.js Express Download File Rest APis",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"download",
"file"
"rest api",
"express"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1"
}
}
Create Controller for download File
In controller package, we create file.controller.js
. It exports 2 functions:
getListFiles()
: read all files in uploads folder, return list of files’ informationn (name, url)download()
: receives file name as input parameter, then uses Express res.download API to transfer the file at path (directory + file name) as an ‘attachment’.
controller/file.controller.js
const fs = require("fs");
const baseUrl = "http://localhost:8080/files/";
const getListFiles = (req, res) => {
const directoryPath = __basedir + "/resources/static/assets/uploads/";
fs.readdir(directoryPath, function (err, files) {
if (err) {
res.status(500).send({
message: "Unable to scan files!",
});
}
let fileInfos = [];
files.forEach((file) => {
fileInfos.push({
name: file,
url: baseUrl + file,
});
});
res.status(200).send(fileInfos);
});
};
const download = (req, res) => {
const fileName = req.params.name;
const directoryPath = __basedir + "/resources/static/assets/uploads/";
res.download(directoryPath + fileName, fileName, (err) => {
if (err) {
res.status(500).send({
message: "Could not download the file. " + err,
});
}
});
};
module.exports = {
getListFiles,
download,
};
Define Route for downloading file
When a client sends HTTP requests, we need to determine how the server will response by setting up the routes.
Create index.js file inside routes folder with content like this:
const express = require("express");
const router = express.Router();
const controller = require("../controller/file.controller");
let routes = (app) => {
router.get("/files", controller.getListFiles);
router.get("/files/:name", controller.download);
app.use(router);
};
module.exports = routes;
You can see that we use controller from file.controller.js.
Create Express app server
Finally, we create an Express server in server.js:
const cors = require("cors");
const express = require("express");
const app = express();
global.__basedir = __dirname;
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
const initRoutes = require("./src/routes");
app.use(express.urlencoded({ extended: true }));
initRoutes(app);
let port = 8080;
app.listen(port, () => {
console.log(`Running at localhost:${port}`);
});
What we do are:
– import express
and cors
modules:
- Express is for building the Rest apis
- cors provides Express middleware to enable CORS with various options.
– create an Express app, then add cors
middlewares using app.use()
method. Notice that we set origin: http://localhost:8081
.
– listen on port 8080 for incoming requests.
Run The App
First we need to create uploads folder with the path resources/static/assets
, then add several files into the folder.
On the project root folder, run this command: node server.js
.
– Retrieve list of Files’ information:
– Now you can download any file from one of the paths above.
For example: http://localhost:8080/files/bezkoder.png
.
Conclusion
Today we’ve learned how to create Node.js Express Rest API to download file to Client with url from server static folder.
Following tutorials explain how to build Front-end Apps to work with our Node.js Express Server:
– Angular 8 Client / Angular 10 Client / Angular 11 Client / Angular 12
– Vue Client / Vuetify Client
– React Client / React Hooks Client
– React Material UI Client
The source code at the end of this post will cover all of APIs including upload files.
Node.js Express File Upload Rest API example using Multer
Happy Learning! See you again.
Further Reading
You can also know way to upload an Excel file and store the content in MySQL database with the post:
Node.js: Upload/Import Excel file data into Database
If you want to upload images into database, you can find instructions at:
– Upload/store images in MySQL using Node.js, Express & Multer
– How to upload/store images in MongoDB using Node.js, Express & Multer
Source Code
You can find the complete source code for this tutorial on Github.
It was very helpful! Thank you!
Thank you so much