Multiple files upload with Angular 2, Express and multer

Ahmed Hamed
Jul 20, 2017 · 3 min read

Le ‘me’ learning Angular 2

I am a two-month software engineer with tendencies to front end development but lately in my journey towards keeping up with the crowd and learning angular (angular shortly refers to angular 2+ now), i have came towards the need of uploading multiple files all at once since i was trying to learn and apply what i learnt in a real project 🙌.
I’ve tried angular 1.x before and i am familiar with node ecosystem (mainly doing tuts and reading blogs about how MEAN stack works 😢).

Always keep this in mind

I came across a solution that does not involve ng related npm packages but multer on the Express side I was kinda stuck since I was only capable of uploading one file and couldn’t be able to find whether the issue was in my back end or front end.

Fancy Talking , show us the code

First things first, lets talk about multer : Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

NOTE: Multer will not process any form which is not multipart (multipart/form-data).

On the blue corner we have Express (app.js)

on the express side, after doing your declarations,

var express = require('express');
var multer = require('multer');
var path = require('path');
var app = express();
var port = 3003;

specify the folder which will contain your files, in our case ‘uploads’ and set your headers and content type

// specify the folder
app.use(express.static(path.join(__dirname, 'uploads')));
// headers and content type
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

next, comes multer with very straight forward examples on the npm website

var storage = multer.diskStorage({
// destination
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage });

Finally, you expose the endpoint which will be attacked on the angular part

app.post("/upload", upload.array("uploads[]", 12), function (req, res) {
console.log('files', req.files);
res.send(req.files);
});

Finally, the famous listening on port …

var server = app.listen(port, function () {
console.log("Listening on port %s...", port);
});

Server is up and running, get to your app folder and type node app.js

On the red corner, Angular 2

Lets start by defining showing the template, a simple form with a an input of type file which will trigger a change in the number of selected files and a button which will trigger the upload() method.
PS : do not forget to add multiple to allow multiple selection.

<input id="cin" name="cin" type="file" (change)="fileChangeEvent($event)" placeholder="Upload a file..." multiple/>// button
<button type="button" class="btn btn-success btn-s" (click)="upload()">
<i class="glyphicon glyphicon-open-file"></i>&nbsp;Upload
</button>

In your angular component, initialize a filesToUpload array as follows, this will serve as a container of the files we chose from our template.

filesToUpload: Array<File> = [];

the upload() and fileChangeEvent() methods are implemented as follows

upload() {
const formData: any = new FormData();
const files: Array<File> = this.filesToUpload;
console.log(files);

for(let i =0; i < files.length; i++){
formData.append("uploads[]", files[i], files[i]['name']);
}

console.log('form data variable : '+ formData.toString());
this.http.post('http://localhost:3003/upload', formData)
.map(files => files.json())
.subscribe(files => console.log('files', files))
}

fileChangeEvent(fileInput: any) {
this.filesToUpload = <Array<File>>fileInput.target.files;
//this.product.photo = fileInput.target.files[0]['name'];
}

the for loop iterates over the number of files chosen and add them to our formdata to be sent to the endpoint we exposed earlier with express.

As simple as that, a full working example of uploading multiple files using angular 2, express and multer.

And as we say in Tunisia, “Jawwek behi … ”

)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade