Uploading files in nodejs using fortjs

Ujjwal Gupta
fortjs
Published in
5 min readApr 9, 2019

Introduction

In this article — i will show you , how we can upload files in nodejs using the framework — fortjs.

I will be using typescript in this article but you can use JavaScript es6 too.

Let’s Code

Project setup

We are going to use fort-creator -a cli tool to help with fortjs development.

Perform the below steps sequentially -

  • Install the fort creator globally — run the command npm i fort-creator -g
  • Create new project — fort-creator new my-app. Here “my-app” is the name of app, you can choose any.
  • Enter into the project directory — cd my-app
  • Start the dev server — fort-creator start
  • Open the url — “http://localhost:4000/

You should see something like this in the browser -

Create Upload Form

We need to create a view which will contain the upload form.

You can see a folder “views” inside the project directory. This folder contains all views. Let’s add a view upload.html inside the default folder of view i.e “views/default”

You may wonder — why the extra folder default ?

This is because — views are arranged controller wise to make things clear. You can see inside the controllers folder , we have a controller with name “DefaultController”. So the views being used by this controller should be kept inside the related folder. There is no hard rule for this, you are free to choose your own folder & rules to keep files.

Copy the below html code inside upload.html

<html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1 style="text-align:center;">FortJs File Uploader Demo</h1>
<br><br>
<form method="POST" action="/default/upload" enctype="multipart/form-data">
<div style="text-align: center;">
<input name="pic" type="file" value="Upload file" />
<br><br><br>
<button type="submit">Submit</button>
</div>
</form>
</body>
</html>

The above code contains a html form. The form contains a input of type file which will be used to upload the file & a button of type submit to send the form.

Create Upload End point

Now, we need an end point to be called from browser , which will render the upload view.

Add the below code inside the DefaultController class located inside the controllers folder.

@Worker(HTTP_METHOD.Get)
@Route("/upload")
async getuploadForm() {
return viewResult("default/upload.html")
}

You can see in the above code :- we are using some decorators like

  • “@Worker” :- The “Worker” add the target method to routes, so that it can be called by using http request. We have supplied value “HTTP_METHOD.Get” inside the Worker. This instructs to make this method call only when http method is “GET”.
  • “@Route” :- The “Route” method is used to customize the route. We have customized the route to “/upload” using Route decorator.
    If we wont customize the route, then by default :- it will take the method name. In our case it will be “getUploadForm”.

I hope above explanation makes things clear. But if not, feel free to ask any question in the comments.

Note :- You might get some reference error due to the variables are not available. Please import them from “fortjs”.

I believe, you have not stopped the development server which we have started in the project setup step. But if you have stopped, restart again by runing the command — fort-creator start

Now, let’s see our upload form. Open the url :- http://localhost:4000/upload

file upload form

I know, you might be wondering. How the url is being constructed here. Let’s see -

There are two parts of url -

  • one from controller :- “default”. The Controller “DefaultController” is associated with route “*”. You can see this inside the routes.ts . The route “*” means when nothing is matched, try me. This is something like default route.
  • one from worker :- “upload”. We have created this url using the decorator “Route”.

that’s why our whole url is “http://localhost:4000/upload”. For more info about routing, please read docs at :- http://fortjs.info/tutorial/route/

Now we need to create the end point for uploading the form. Copy the below code & paste inside the “DefaultController”

@Worker(HTTP_METHOD.Post)
@Route("/upload")
async uploadFile() {
if (this.file.count > 0) {
const file = this.file.files[0];
const pathToSave = Path.join(__dirname, `../upload/${file.originalFilename}`);
await this.file.saveTo(file.fieldName, pathToSave);
return textResult("file saved");
} else {
return textResult("no files is supplied in the request");
}
}

In the above code -

  • We have created a method “uploadFile” which have end point “/upload” but this will work for only http method Post. We are restricting this to http method post by supplying the parameter “POST” in the decorator Worker.
  • We are using `this.file`. fileis member of controller which holds the info about the files in the http request.
  • We are checking the count of files by using the count property.
  • The property files contains the all files. We are grabbing the first file by using the index 0.
  • We are saving this file to a directory by using the file property “saveTo”. saveTo takes the name of the input field which is “pic” in our case (check in the view for the input type file) & the location to save the file. We are specifying the upload folder in the project directory to save the file.

Now, let’s try uploading of file. Open the url :- http://localhost:4000/upload & upload a file

You will get the output “file saved” upon successful save. You can see the uploaded file inside the upload directory of project.

This was is the end of the article 😬. Hope you have liked it. Don’t forget to hit the clap button. Thanks !

References

--

--

Ujjwal Gupta
fortjs
Editor for

Frontend lead Polygon | Creator of jsstore, mahaljs | sqlweb, fortjs | opensource creator | we3, blockchain, solidity | javascript