Friday 2 June 2017

Error 400 uploading file using angularJS and nodeJS

I am trying to upload a sound with AngularJS but I get this error when posting the data.

POST http://localhost:2000/upload 400 (Bad Request)

I don't know what is the issue. Is it the formdata that I need to change?

This is the code :

HTML:

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

AngularJS Controller:

$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.");
                }                       
            }
            console.log(formData.getAll("uploads[]"));
            $http.post('/upload', formData).then(function(response){
                console.log("Uploaded :");
                console.log(response.data);
            });
        }
    } 
}

NodeJS:

app.post('/upload', function(req, res){
// create an incoming form object
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, './public/database');

// 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