Search code examples
node.jsmongodbfile-uploadgridfs-streamrequestjs

nodeJS file upload using request library


I am trying to upload a file to a server (built using Java) by reading from a mongodb gridfs stream.

exports.upload = function(req, res, next) {
var IHUrl = config.api.url + "PhotosServlet";


var data = req.body;

var file1 = api.gfs.createReadStream({
    _id: data.fileId
})

var formData = {
    "imgTyp": data.imgTyp,
    "listingid": data.listingid,
    "scaleTech": data.scaleTech,
    "SPC": data.SPC,
    "SPCUID": data.SPCUID,
    "varRand": data.varRand,
    "file1": file1
};

var r = request.post({
    url: IHUrl,
    formData: formData
}, function(error, IHResponse, body) {
    if (error) {
        res.send(500, error);
        console.log("Error occured uploading file1")
    } else {
        console.log("Upload successful", IHResponse);
        res.send(200, IHResponse);
    }
});
next();
};

File is already uploaded in mongodb gridfs before I start uploading the file to upstream server.

I am using following nodejs libraries:

request, gridfs-stream

I am getting the following error from upstream server:

javax.servlet.ServletException: Processing of multipart/form-data request failed. Stream ended unexpectedly

What could be going wrong here?


Solution

  • I realized that its been a while and its a problem some of you may encounter and the solution was not really what I posted in the comments as I found more problems later. The issue that we had was that the java servlet that we were posting the multipart form data was not able to handle chunked data and setting headers won't do you any good. using request library will not help you here. I had to make use of restler (https://www.npmjs.com/package/restler) to send the entire multipart data in a single chunk.