Example file upload in express

1. create file uploadFile.html

 

<!DOCTYPE html>

<html>

    <head>

        <title>Simple Upload Example</title>

    </head>

    <body>

        <form action="/upload" enctype="multipart/form-data" method="post">

            <input type="file" name="upload" multiple>

            <input type="submit" value="Upload">

        </form>

    </body>

</html>

 

2. create file success.html

 

<html>

    <body>

        <h1>Home</h1>

        <p>File upload success</p>

    </body>

</html>

 

3. create file express_upload_file.js

 

var express = require('express');

var formidable = require('formidable');

 

var app = express();

 

app.get('/', function (req, res) {

    res.sendFile(__dirname + '/uploadFile.html');

});

 

app.post('/upload', function (req, res) {

    var form = new formidable.IncomingForm();

 

    form.parse(req);

 

    form.on('fileBegin', function (name, file) {

        file.path = __dirname + '/uploads/' + file.name;

    });

 

    form.on('file', function (name, file) {

        console.log('Uploaded ' + file.name);

    });

 

    res.sendFile(__dirname + '/success.html');

});

 

app.listen(8080);

 

Run and go browser: http://localhost:8080

Add images and submit: