To upload files in Angular, use the ng2-file-upload library. For managing the uploaded files at the backend, we use the multer library. Multer is a node.js middleware for handling multipart/form-data, primarily for uploading files.
Here is the step-by-step guide to upload a file in Angular.
Step 1: Install Angular.
npm install -g @angular/cli
# or
yarn add global @angular/cli
Create a local project using the following command.
ng new fileupload
Start the application using the following command.
ng serve --open
Step 2: Install the rxjs-compat library.
npm install rxjs-compat --save
Step 3: Install Bootstrap 4.
Go to your terminal and type the following command.
npm install bootstrap --save
After that, go to the inside src folder, open the styles.css file, and import the bootstrap.min.css file.
@import "~bootstrap/dist/css/bootstrap.min.css"
Step 4: Install the ng-file-upload library.
Type the following command to install the library.
npm install ng2-file-upload --save
Write the following code inside an app.module.ts file.
// app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FileSelectDirective } from 'ng2-file-upload'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, FileSelectDirective ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Write the following code inside an app.component.ts file.
// app.component.ts import { Component, OnInit } from '@angular/core'; import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload'; const URL = 'http://localhost:3000/api/upload'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'}); ngOnInit() { this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; }; this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => { console.log('ImageUpload:uploaded:', item, status, response); alert('File uploaded successfully'); }; } }
Write the following code inside an app.component.html file.
<input type="file" name="photo" ng2FileSelect [uploader]="uploader" /> <button type="button" class="btn btn-success btn-s" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length" > Upload an Image </button>
Step 5: Create Node.js backend.
Install the following node modules.
npm install express multer body-parser --save
We have installed Express as a web framework for Node.js development.
Install nodemon as a dev dependency.
npm install nodemon --save-dev
Create a new directory inside the root called uploads.
Create one file in the project root folder called server.js.
// server.js const path = require('path'); const fs = require('fs'); const express = require('express'); const multer = require('multer'); const bodyParser = require('body-parser') const app = express(); const router = express.Router(); const DIR = './uploads'; let storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, DIR); }, filename: (req, file, cb) => { cb(null, file.fieldname + '-' + Date.now() + '.' + path.extname(file.originalname)); } }); let upload = multer({storage: storage}); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200'); res.setHeader('Access-Control-Allow-Methods', 'POST'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.setHeader('Access-Control-Allow-Credentials', true); next(); }); app.get('/api', function (req, res) { res.end('file catcher example'); }); app.post('/api/upload',upload.single('photo'), function (req, res) { if (!req.file) { console.log("No file received"); return res.send({ success: false }); } else { console.log('file received'); return res.send({ success: true }) } }); const PORT = process.env.PORT || 3000; app.listen(PORT, function () { console.log('Node.js server is running on port ' + PORT); });
Boot up the server using the following command.
nodemon server
Step 6: Run the project.
Start both servers if not started.
- ng server –open
- nodemon server
Go to the http://localhost:4200/
Once you select any file, the upload an image button will remain disabled.
Upload an image, and see your response in the browser console.
When encountering an error, Multer will delegate the error to Express. Thus, you can display a nice error page using the standard expressway.
To catch errors specifically from Multer, you can call the middleware function yourself. Also, if you’re going to catch only the Multer errors, you can use the MulterError class that is attached to the multer object itself (e.g. err instanceof multer.MulterError
).
// server.js var multer = require('multer') var upload = multer().single('avatar') app.post('/profile', function (req, res) { upload(req, res, function (err) { if (err instanceof multer.MulterError) { // A Multer error occurred when uploading. } else if (err) { // An unknown error occurred when uploading. } // Everything went fine. }) })
That’s it for this tutorial. Thanks for taking it.
Brian S
Great tutorial. Working perfect.
Troy
How to display the images after they are stored
Robin Singh
I watched many tutorials but u r the best.
i m trying from last 2 weeks but nothing happens. Thanku for this tutorial.
Can u make a new tutorial on how to show image after save in folder and database
Ganesh
Is this work in a2hosting or Godaddy server? In the local server it is working fine.
Gopi
This is what I am exactly looking for. Got it. Great thanks Krunal.
Nize
Thank you so much.
mohan
not working for me .anyone please help me
send me tour code to amohanagarapu@gmail.com
prasanna
carefully follow every command, even it didn’t worked for me in the beginning
jaballi aymen
thkns for that 🙂
but how get link this image uplouder!!
bhawna inaniya
please perform this operation with form data
bhawna inaniya
please send detail about how to add post data with ng2 uploader
Almeida
How can I show the image that was uploaded? To upload an image is easy, but I don`t get how can I fetch it and show it 🙁
Pankaj Makwana
Can you please let me know how to send header with file uploading? I want to send authentication token, and other headers
best iptv
bonjour
great share.
I think the most stable premium iptv servers are those from Fishbone IPTV cloud
I would like to see more posts like this
Thanks
Mohamed Motyim
Thanks a lot this help me
Aditya
Getting 404 error while using same with spring rest api on angular 6
Rozy Mahsun
How to upload multiple files ?
Thanks in advanec
Mladen
UploadCatalogComponent.html:8 ERROR TypeError: Cannot read property ‘uploadAll’ of undefined
Katheeja
has no exported member ‘FileSelectDirective’.Why I get this error?
Katheeja
Thanks a lot, How to do file download from server using angular and node.js.Please share snippet.
Katheeja
Thanks a lot,upload worked but I am unable to download in original file name. Please help.
Nhi
Hi, I have an error: OPTIONS http://localhost:3000/image net:: ERR_CONNECTION_REFUSED
Please help me. Thanks
jeevanandan
I need to send form values also, how can i send?
jk
where is the file stored after uploading
jk
where is the file stored after uploading
Esteban Potes Rua
in the uploads folder
cvvb
where is the upload folder
Esteban Potes Rua
How to use the download of those files?
Shah Maz
I got another issue. after running server.js upload works perfect but I got 404 Err ‘File NOT found’ from another method I already have.
this.httpClnt.get (‘assets/daily.json’); //it works before running server.js but after running httpClient Get json files not working
any idea
Nethravathi
Can any please help me with the code to upload csv and xlsx file in angular 6?
imran
how to upload csv file into mongodb in mean stack angular 7
mounika
It’s not working for me can you please any share code.
sathya
It’s working fine up to UI but it’s not working in services part for me
Ex: in my project i am getting service path http://localhost:3000/api/upload always not found 404 error
Can you please any one help me for this.
rgreerre
updating image how can it be done
yutu
ye i want to know
chaitanya
ng build –prod getting error:
Please consider moving FileSelectDirective in node_modules/ng2-file-upload/file-upload/file-select.directive.d.ts to a higher module that imports AppModule in src/app/app.module.ts and FileUploadModule in node_modules/ng2-file-upload/file-upload/file-upload.module.d.ts. You can also create a new NgModule that exports and includes FileSelectDirective in node_modules/ng2-file-upload/file-upload/file-select.directive.d.ts then import that NgModule in AppModule in src/app/app.module.ts and FileUploadModule in node_modules/ng2-file-upload/file-upload/file-upload.module.d.ts.
Peters Chikezie
Great post. Is there a way to send both and image and other form fields to node server?
Utsah
Can upload video using file upload?
David
Adding ‘FileSelectDirective’ to the declarations in app.module.ts produces loads of errors for me.