node-formidable / formidable

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
MIT License
7.06k stars 683 forks source link

Support for Base64 Content-Transfer-Encoding #80

Closed ghost closed 13 years ago

ghost commented 13 years ago

We needed to parse base64-encoded attachments, so we wrote a quick patch to formidable to handle 'em. It's a complete hack without any test cases, but I figured I'd throw it upstream anyway, in case someone else needs the feature (or has the time to implement it as a proper patch with test cases and stuff)

index 62c9e3b..2dc52c3 100644
--- a/dep/node_formidable/lib/incoming_form.js
+++ b/dep/node_formidable/lib/incoming_form.js
@@ -256,6 +256,8 @@ IncomingForm.prototype._initMultipart = function(boundary) {
     part.name = null;
     part.filename = null;
     part.mime = null;
+    part.encoding = null;
+    part.base64Buf = '';
     headerField = '';
     headerValue = '';
   };
@@ -283,6 +285,8 @@ IncomingForm.prototype._initMultipart = function(boundary) {
       }
     } else if (headerField == 'content-type') {
       part.mime = headerValue;
+    } else if (headerField == 'content-transfer-encoding') {
+      part.encoding = headerValue;
     }

     headerField = '';
@@ -294,7 +298,14 @@ IncomingForm.prototype._initMultipart = function(boundary) {
   };

   parser.onPartData = function(b, start, end) {
-    part.emit('data', b.slice(start, end));
+    if (part.encoding === 'base64') {
+      part.base64Buf += b.toString('ascii', start, end);
+      var excess = part.base64Buf.length % 4;
+      part.emit('data', new Buffer(part.base64Buf.slice(0, excess ? -excess : undefined), 'base64'
+      part.base64Buf = excess ? part.base64Buf.slice(-excess) : '';
+    } else {
+      part.emit('data', b.slice(start, end));
+    }
   };

   parser.onPartEnd = function() {

Patch is against felixge/node-formidable@6b9ffe3653fe59f035b01ba1f46b5f2650be00ca

felixge commented 13 years ago

I'll be happy to look at anything, but stuff that's not tested will take me longer to merge : )