3

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!

George Jor
  • 501
  • 1
  • 7
  • 18
  • This [topic](https://stackoverflow.com/questions/23691194/node-express-file-upload) already shared the correct answer so might It is helpful. – Hiren Sanja Dec 20 '22 at 13:12
  • This [topic](https://stackoverflow.com/questions/23691194/node-express-file-upload) already shared the correct answer so might It is helpful. – Hiren Sanja Dec 20 '22 at 13:13
  • This [topic](https://stackoverflow.com/questions/23691194/node-express-file-upload) already shared the correct answer so might It is helpful. – Hiren Sanja Dec 20 '22 at 13:17

3 Answers3

3

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

Dayan Moreno Leon
  • 5,357
  • 2
  • 22
  • 24
  • Are you sure I can use .path? as I got the following result: TypeError: Cannot read property 'path' of undefined – George Jor May 17 '14 at 14:09
  • is not about path is about the file name that it doesn't exists. you can console log your req.files and see whats in it, thumbnail should be your files name – Dayan Moreno Leon May 17 '14 at 14:11
  • file: { webkitRelativePath: '', lastModifiedDate: '2014-05-05T02:26:11.000Z', name: '2014-05-05 10.26.11.jpg', type: 'image/jpeg', size: 1310720 }, title: 'tfuyiboinini' } this is what I got and it dun contain any path method or property inside and that make me cry – George Jor May 17 '14 at 14:20
  • what version of express are you using? – Dayan Moreno Leon May 17 '14 at 15:30
0

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');
        });
    });
});
Dalorzo
  • 19,834
  • 7
  • 55
  • 102
0

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');
            });
        });
    });
Hiren Sanja
  • 61
  • 1
  • 4