File Upload
Files are data that a user has such as images, videos, documents, and so on. Unlike the standard form data uploading a file takes a little more configuration due to its format and security. We will see how we can upload files with Node.js.
List of Contents
Creating a Server
Creating a Server with Node.js
The web server contains all the information about the application and allows users to access the data. Typically, getting the request and sending the data is done with HTTP(S), and today we will see the ways to create a server using the native Node.js modu
jin-co.tistory.com
Using Multer
Open the project console and install the packages
npm i multer
Create a folder to store images
Server Configurations
To use static files, we have to specify the path for them. Use 'express.static' and 'path' to do that. ('path' uses the alternate path specified, '/backend/images', when users' request comes to the path, '/images')
const express = require('express')
const app = express()
const path = require('path')
app.use('/images', express.static(path.join('/backend/images')))
Multer Configurations
Mime type is the format of a file. we can alter them as an option as shown below.
const MIME_TYPE = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
}
We can use diskStorage to set the destination of files and their name.
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE[file.mimetype]
let error = new Error('invalid')
if (isValid) {
error = null
}
cb(error, 'backend/images')
},
filename: (req, file, cb) => {
const name = file.originalname.toLowerCase().split(' ').join('-')
const ext = MIME_TYPE[file.mimetype]
cb(null, name + '-' + Date.now() + '.' + ext)
}
})
module.exports = multer({ storage: storage }).single('image')
Testing - Server
Open Postman and create a POST request with a form data in its body (Don't forget to type in keys -> if you don't see the input box, drag the table to widen)
Stored image
Working with the Front
Now that we have created a server, let's see how we can send data from the front end to the server using frameworks.
Angular
With Angular, we will use the reactive forms to upload files
Reactive Form Setup
Angular Forms - Reactive Form
Angular reactive forms uses observables to manage input data in a stream. Unlike the template-driven forms, reactive forms handles the data synchronously and uses operators to manipulate data as a copy but do not change the orginal data Let's see how to us
jin-co.tistory.com
Template Setup
Add a form in the template file to upload a file
<form [formGroup]="form" (submit)="onSubmit()">
<img [src]="imgPreview" alt="" height="100px">
<input type="file" hidden (change)="onFileLoad($event)" #loader>
<button mat-icon-button type="button" (click)="loader.click()">+</button>
<button mat-stroked-button>Add</button>
</form>
Class File Setup
Add the code below to the class file to handle the file submitted.
1. Initialization of a form group and controller
form!: FormGroup;
constructor() {
this.form = new FormGroup({
image: new FormControl(''),
});
}
2. Storation of the uploaded files and preview code.
imgPreview: string = '';
onFileLoad(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0];
this.form.patchValue({ image: file });
this.form.get('image')?.updateValueAndValidity();
const reader = new FileReader();
reader.onload = () => {
this.imgPreview = reader.result as string;
};
reader.readAsDataURL(file as Blob);
}
Finally, a request to the server (In this example, I used a service class)
//post.service.ts
url: string = environment.url + 'posts/';
addPost(title: string, content: string, image?: File) {
post = new FormData();
post.append('title', title);
post.append('content', content);
post.append('image', image, title);
this.https.post(this.url, post).subscribe((result) => {
});
}
In this writing, we have seen how we can store files with Node.js
References
multer
Middleware for handling `multipart/form-data`.. Latest version: 1.4.5-lts.1, last published: a year ago. Start using multer in your project by running `npm i multer`. There are 3787 other projects in the npm registry using multer.
www.npmjs.com