George Jor
George Jor

Reputation: 511

Store the uploaded files into file system in Express Js

I am new to nodejs and want to know how to put a file into my system backend or even upload it to S3 etc.

Here are the file object:

req.body { homeColor: 'black',
  guestColor: 'white',
  thirdColor: 'red',
  file: 
   { webkitRelativePath: '',
     lastModifiedDate: '2014-05-05T02:26:11.000Z',
     name: '2014-05-05 10.26.11.jpg',
     type: 'image/jpeg',
     size: 1310720 },
  title: 'tfuyiboinini' }

How to handle req.body.file so that it can be physically saved?

Please help and thanks!

Upvotes: 3

Views: 8909

Answers (3)

Hiren Sanja
Hiren Sanja

Reputation: 91

This topic already shared the correct answer so might It is helpful.

Also, please find the below solution.

var express = require('express');
var busboy = require('connect-busboy');
var path = require('path'); 
var fs = require('fs-extra');

var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));


app.route('/fileupload')
    .post(function (req, res, next) {

        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file, filename) {
            console.log("Uploading: " + filename);

            //Path where image will be uploaded
            fstream = fs.createWriteStream(__dirname + '/img/' + filename);
            file.pipe(fstream);
            fstream.on('close', function () {    
                console.log("Uploading process finish " + filename);              
               // res.redirect('back');
            });
        });
    });

Upvotes: 0

Dalorzo
Dalorzo

Reputation: 20014

First make sure your POST is encoded as enctype="multipart/form-data"....

In Express 4 you need to set the body parser in your server:

var bodyParser     = require('dy-parser');
//...

var app            = express();
//...
app.use(bodyParser());  // pull information from html in POST

var busboy = require('connect-busboy');    
app.use(busboy());

In earlier version of Express you only needed to add the body parser from the framework itself and files will be store on the configured location:

     app.use(express.bodyParser({limit: '10mb', uploadDir: __dirname + '/public/uploads' }));               // pull information from html in POST

Since version 4 removed support for connect now you need to add your custom support for multipart/form data to parser multi/part POSTs, so you will have to to do something like:

var fs = require('fs');
var busboy = require('connect-busboy');

//...
app.use(busboy()); 
//...
app.post('/fileupload', function(req, res) {
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file, filename) {
        console.log("Uploading: " + filename); 
        fstream = fs.createWriteStream(__dirname + '/files/' + filename);
        file.pipe(fstream);
        fstream.on('close', function () {
            res.redirect('back');
        });
    });
});

Upvotes: 0

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

long story short

var fs = require('fs');
app.post('/file-upload', function(req, res) {
    var tmp_path = req.files.thumbnail.path;
    var target_path = './public/images/' + req.files.thumbnail.name;
    fs.rename(tmp_path, target_path, function(err) {
        if (err) throw err;
        fs.unlink(tmp_path, function() {
            if (err) throw err;
            res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
        });
   });
};

you can read more about it here: http://www.hacksparrow.com/handle-file-uploads-in-express-node-js.html

Upvotes: 3

Related Questions