Browsed by
Tag: formidable

Error: MultipartParser.end(): stream ended unexpectedly: state = START

Error: MultipartParser.end(): stream ended unexpectedly: state = START

It’s been over a year since I last wrote! Wow. I finally hit a bug so frustrating that I couldn’t not write about it. Haha.

File uploads in Node.js with Express 4 and Formidable

As you probably know, in Express 4, bodyParser was removed and must be included as a module.

Furthermore, file uploads (multipart/form-data) via req.files is no longer supported. So, a module like formidable or multiparty must be used to parse the data. Fortunately, it’s super simple. You can set up a route like this:

Just grab a form object, set a few preferences, and call parse. The file(s) are saved to your upload directory and the associated metadata is returned in files. However, you may receive an err that reads Error: MultipartParser.end(): stream ended unexpectedly: state = START. That means the connection ended before the file(s) finished transferring… but why?

It took me a long time to figure this one out. I noticed that if I utilized the raw-body module, the problem went away. No idea why, though. Something to do with reading the stream completely, I guess. I tried using the multiparty module instead, but it returned a similar error. Then, it occurred to me that Nginx could be botching the upload somehow! But, hitting the node server directly didn’t help.

Finally, I found it. The second line in the code above. res.send(200) should be within the formidable callback. Calling it at the beginning of the route sends a response before the upload is complete, thus… terminating the connection early. Arggggg!! It’s times like these when I feel like I should just find another line of work. Haha. But, that’s just how it goes sometimes… 🙂