0

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?

Prabhat
  • 4,066
  • 4
  • 34
  • 41
  • Try to remove `next();` – Vladimir G. Apr 01 '16 at 10:22
  • Thanks mate for the suggestion. I tried adding headers: {"transfer-encoding": "chunked"}, to the headers and it worked without complaint. – Prabhat Apr 01 '16 at 10:30
  • This is how it will look like: request.post({ url: IHUrl, headers: {"transfer-encoding": "chunked"}, formData: formData } – Prabhat Apr 01 '16 at 10:30
  • I'm glad it works but I think you should remove `send()` anyway. I think you use it as a route in express app. So `send()` will be called before your post request completed. Then it will be passed down the stack and if you have e.g. middlewares for handling 404, error will be returned – Vladimir G. Apr 01 '16 at 10:35

1 Answers1

0

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.

Prabhat
  • 4,066
  • 4
  • 34
  • 41