Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload file with nodeJS

Tags:

I am having trouble uploading a file with nodeJS and Angular.

I found solutions but it's only with Ajax which I don't know about. Is it possible to do without?

With the following code I get this error :

POST http://localhost:2000/database/sounds 413 (Payload Too Large)

Code:

HTML:

<div class="form-group">
        <label for="upload-input">This needs to be a .WAV file</label>
        <form enctype="multipart/form-data" action="/database/sounds" method="post">
            <input type="file" class="form-control" name="uploads[]" id="upload-input" multiple="multiple">
        </form>
        <button class="btn-primary" ng-click="uploadSound()">UPLOAD</button>
    </div>

Javascript:

$scope.uploadSound = function(){
    var x = document.getElementById("upload-input");
    if ('files' in x) {
        if (x.files.length == 0) {
            console.log("Select one or more files.");
        } else {
            var formData = new FormData();
            for (var i = 0; i < x.files.length; i++) {
                var file = x.files[i];
                if(file.type==("audio/wav")){
                    console.log("Importing :");
                    if ('name' in file) {
                        console.log("-name: " + file.name);
                    }
                    if ('size' in file) {
                        console.log("-size: " + file.size + " bytes");
                    }
                    formData.append('uploads[]', file, file.name);
                }else{
                    console.log("Error with: '"+file.name+"': the type '"+file.type+"' is not supported.");
                }  
            }
            $http.post('/database/sounds', formData).then(function(response){
                console.log("Upload :");
                console.log(response.data);
            });

        }
    } 
}

NodeJS:

//Upload a sound
app.post('/database/sounds', function(req, res){
  var form = new formidable.IncomingForm();

  // specify that we want to allow the user to upload multiple files in a single request
  form.multiples = true;

  // store all uploads in the /uploads directory
  form.uploadDir = path.join(__dirname, '/database/sounds');

  // every time a file has been uploaded successfully,
  // rename it to it's orignal name
  form.on('file', function(field, file) {
    fs.rename(file.path, path.join(form.uploadDir, file.name));
  });

  // log any errors that occur
  form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
  });

  // once all the files have been uploaded, send a response to the client
  form.on('end', function() {
    res.end('success');
  });

  // parse the incoming request containing the form data
  form.parse(req);
});

EDIT:

The error became

POST http://localhost:2000/database/sounds 400 (Bad Request)
like image 451
Chococo35 Avatar asked May 31 '17 11:05

Chococo35


2 Answers

If your are using bodyParser

app.use(bodyParser.urlencoded({limit: '100mb',extended: true}));
app.use(bodyParser.json({limit: '100mb'}));

This will allow you to upload files upto 100mb

like image 56
Dinesh undefined Avatar answered Sep 22 '22 10:09

Dinesh undefined


For json/urlencoded limit, it’s recommended to configure them in server/config.json as follows:

{
“remoting”: {
“json”: {“limit”: “50mb”},
“urlencoded”: {“limit”: “50mb”, “extended”: true}
}

Please note loopback REST api has its own express router with bodyParser.json/urlencoded middleware. When you add a global middleware, it has to come before the boot() call.

var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();

//request limit 1gb
app.use(loopback.bodyParser.json({limit: 524288000}));
app.use(loopback.bodyParser.urlencoded({limit: 524288000, extended: true}));
like image 30
Manoj Patidar Avatar answered Sep 23 '22 10:09

Manoj Patidar