Wednesday, 31 May 2017

Upload file with nodeJS

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?

Also, how can I do to verify that the file is a .WAV file?

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>
        <input type="file" enctype="multipart/form-data" class="form-control" name="uploads[]" id="upload-input" multiple="multiple">
        <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 ('name' in file) {
                    console.log("name: " + file.name + "<br>");
                }
                if ('size' in file) {
                    console.log("size: " + file.size + " bytes <br>");
                }
                formData.append('uploads[]', file, file.name);
            }
            $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);
});



via Chococo35

No comments:

Post a Comment