David Duffrin
David Duffrin

Reputation: 87

How to POST file via jQuery to nodejs connect-busboy

I can successfully send a file to connect-busboy by using an HTML form's action attribute like so:

<form ref='uploadForm' method="post" action="http://localhost:3000/fileupload" enctype="multipart/form-data" id='uploadForm'>
  Select file to upload:
  <input type="file" name="sampleFile">
  <input type="submit" value="Upload!">
</form>

However, I would prefer to not have my page redirect.

I tried to convert this to jQuery by removing the action attribute in the form tag and adding an onclick function with the following:

$.ajax({
        url:'http://localhost:3000/fileupload',
        type:'post',
        contentType: 'multipart/form-data',
        data:$('#uploadForm').serialize(),
        success:function(){
            alert('Success');
        },
        error: function() {
            alert('Error');
        },
});

Unfortunately, this doesn't work with the error:

TypeError: Cannot read property 'end' of undefined

The Nodejs code is as follows:

const express = require('express');
const busboy = require('connect-busboy');
const app = express();
app.use(busboy());
const fs = require('fs');

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/' + filen ame);
        console.log(fstream);
        file.pipe(fstream);
        fstream.on('close', function () {
            res.send('Success');
        });
    });
});

var port = process.env.PORT || 3000;
app.listen(port);

Full error: https://i.sstatic.net/cO9MU.png

Upvotes: 0

Views: 788

Answers (1)

mscdex
mscdex

Reputation: 106736

By explicitly serializing the form you are implicitly avoiding/removing the multipart/form-data format. Instead, pass a FormData instance as the data. You can instantiate a new FormData from an existing form like:

var data = new FormData($('#uploadForm')[0]);

$.ajax({
    url: 'http://localhost:3000/fileupload',
    type: 'POST',
    contentType: false,
    processData: false,
    cache: false,
    data: data,
    success: function() {
        alert('Success');
    },
    error: function() {
        alert('Error');
    }
});

Upvotes: 2

Related Questions