API Upload and Download using LoopBack4

NSerus
4 min readMay 4, 2021

Hello Peppos!!!!

So you want to upload and downloads files from your API, worry no more cause in this tutorial we are going to implement a solution that does exactly that using LoopBack 4.

Getting the Packages and Creating the project

First things first, get the Loopback 4 Package to start building the API.

npm install -g @loopback/cli

Then to create a new project:

lb4 app

Answer the following questions this way for the App(or conforming to your project needs):

? Project name: Upload-Download
? Project description: An API made with LoopBack 4.
? Project root directory: (upload-download)
? Application class name: (UploadApplication)
? Select features to enable in the project:
◉ Enable eslint: add a linter with pre-configured lint rules
◉ Enable prettier: install prettier to format code conforming to rules
◉ Enable mocha: install mocha to run tests
◉ Enable loopbackBuild: use @loopback/build helpers (e.g. lb-eslint)
◉ Enable vscode: add VSCode config files
◉ Enable docker: include Dockerfile and .dockerignore
◉ Enable repositories: include repository imports and RepositoryMixin
◉ Enable services: include service-proxy imports and ServiceMixin
# npm will install dependencies now
Application Upload-Download was created in upload-download.

Now you need to go to the Project’s folder (using the cdcommand) and create a controller class with the name FileUpload.

lb4 controller

Before we code this controller, we will inject an instance of FileUploadService, it is backed by multer to process the incoming http request.

“Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. ” — https://github.com/expressjs/multer

To install multer use the following command:

npm i --save-dev @types/multer

Now that we have finished the building of the project we can do some code.

Coding the Upload part

In the src directory, we need to create types.ts and keys.ts and 1 directory (services) with 2 files, those are index.ts and file-upload.service.ts.

types.ts

After creating the file src/types.ts insert the following code:

import {RequestHandler} from 'express-serve-static-core';export type FileUploadHandler = RequestHandler;

keys.ts

Again, after creating the file src/keys.ts insert the following code:

import {BindingKey} from '@loopback/core';
import {FileUploadHandler} from './types';// Binding key for the file upload service
export const FILE_UPLOAD_SERVICE =
BindingKey.create<FileUploadHandler>('services.FileUpload',);// Binding key for the storage directory
export const STORAGE_DIRECTORY = BindingKey.create<string>
('storage.directory');

Inside the src/servicesdirectory after creating the files add the following code:

file-upload.service.ts

index.ts

After this we need to go back a directory to add code to…

file-upload.controller.ts

Application.ts

To end the upload part we need to edit the application.ts file:

...
} from '@loopback/rest-explorer';
import multer from 'multer';
...
import path from 'path';
import{FILE_UPLOAD_SERVICE,STORAGE_DIRECTORY} from './keys';
...
export class FileTransferApiApplication extends BootMixin(
ServiceMixin(RepositoryMixin(RestApplication)),
) {
constructor(options: ApplicationConfig = {}) {
...
this.component(RestExplorerComponent); // Configure file upload with multer options
this.configureFileUpload(options.fileStorageDirectory);
...
}
///////////////final of the FileTransferApiApplication class:

protected configureFileUpload(destination?: string) {
// Upload files to `dist/.sandbox` by default
destination = destination ?? path.join(__dirname, '../.sandbox');
this.bind(STORAGE_DIRECTORY).to(destination);
const multerOptions: multer.Options = {
storage: multer.diskStorage({
destination,
// Use the original file name as is
filename: (req, file, cb) => {
cb(null, file.originalname);
},
}),
};
// Configure the file upload service with multer options
this.configure(FILE_UPLOAD_SERVICE).to(multerOptions);
}
}

Coding the Download part

Don’t worry the hard part is over now…

The same way we did with Upload, we need to create a controller for the File Download with:

lb4 controller

Call the controller FileDownload and add this code:

You may now test the API using explorer, but i prefer adding the final html code for a website to test the upload and download.

Adding Visuals

In the public directory in the index.html, replace the code with the following code:

Now we can test this…

Testing…

To test the app simply upload a file, add a description if you want and submit:

uploading a new file

I submitted 2 to show that it has the capability for more that one file.

Now you can download by clicking the file that you want:

files to download
File downloaded

--

--