0

I'm using busboy to stream jpg image to a node server. But the issue is everytime i try to upload a file from client with Postman, it fails with the following error:

[info] >  Busboy error catching......>>>>>>>>>>>>>> Error: Unexpected end of multipart data
[info] >      at C:\Users\ismail\Documents\Archive\tutorial-codes\NanoRD\proj3\proj3\functions\node_modules\dicer\lib\Dicer.js:61:28
[info] >      at processTicksAndRejections (internal/process/task_queues.js:81:9)
[info] >  fstream error catching......>>>>>>>>>>>>>> Error: Part terminated early due to unexpected end of multipart data
[info] >      at C:\Users\ismail\Documents\Archive\tutorial-codes\NanoRD\proj3\proj3\functions\node_modules\dicer\lib\Dicer.js:64:36
[info] >      at processTicksAndRejections (internal/process/task_queues.js:81:9)

trace: node_modules\dicer\lib\Dicer.js:64:36

Dicer.prototype.emit = function(ev) {
   if (ev === 'finish' && !this._realFinish) {
    if (!this._finished) {
      var self = this;
      process.nextTick(function() {
        self.emit('error', new Error('Unexpected end of multipart data'));
        if (self._part && !self._ignoreData) {
          var type = (self._isPreamble ? 'Preamble' : 'Part');
          self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'));
          self._part.push(null);
          process.nextTick(function() {
            self._realFinish = true;
            self.emit('finish');
            self._realFinish = false;
          });
          return;
        }
        self._realFinish = true;
        self.emit('finish');
        self._realFinish = false;
      });
    }
  } else
    WritableStream.prototype.emit.apply(this, arguments);
};

I tried adding an 'error' handler for file in the 'file' event handler and also in the uploadImage handler

here's my code:

exports.uploadImage = (req, res) => {
   BusBoy = require("busboy"),
   path = require("path"),
   os = require("os"),
   fs = require("fs");

  const busboy = new BusBoy({ headers: req.headers });

  let imageToBeUploaded = {}, imageFileName;

  busboy.on("error", function(err) {
    console.log("Busboy error catching......>>>>>>>>>>>>>>", err);
  });

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {

    if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
       return res.status(400).json({ error: "Wrong file type submitted" });
    }

    file.on("error", function(err) {
      console.log("fstream error catching......>>>>>>>>>>>>>>", err);
    });

    const imageExtension = filename.split(".")[filename.split(".").length - 1];

    // 32756238461724837.png
    imageFileName = `${Math.round(
      Math.random() * 1000000000000
    ).toString()}.${imageExtension}`;

    const filepath = path.join(os.tmpdir(), imageFileName);
    imageToBeUploaded = { filepath, mimetype };
    file.pipe(fs.createWriteStream(filepath));
  });

  busboy.on("finish", () => {

    admin
      .storage()
      .bucket()
      .upload(imageToBeUploaded.filepath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: imageToBeUploaded.mimetype
          }
        }
      })
      .then(() => { 

        const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${
      config.storageBucket
    }/o/${imageFileName}?alt=media`;

        // access req.user.uid from fbAuth middleware
        return db.doc(`/users/${req.user.uid}`).update({ imageUrl });
      })
      .then(() => {
        return res.json({ message: "image uploaded successfully" });
      })
      .catch(err => {
        console.error(err);
        return res.status(500).json({ error: "something went wrong" });
      });
  });


  busboy.end(req.rawBody);
};

Postman Request:

POST /would-you-rather-app-c5895/us-central1/api/user/image HTTP/1.1
Host: localhost:5000
Content-Type: multipart/form-data; boundary=----XXXX
Authorization: Bearer <XXXX>
User-Agent: PostmanRuntime/7.13.0
Accept: */*
Cache-Control: no-cache
Postman-Token: <XXXX>
Host: localhost:5000
accept-encoding: gzip, deflate
content-length: 7411
Connection: keep-alive
cache-control: no-cache


Content-Disposition: form-data; name="File"; filename="/C:/Users/ismail/Desktop/nas.jpg


------WebKitFormBoundary7MA4YWxkTrZu0gW--

I expect an image file upload to my firebase storage bucket instead i get only the file metadata

Ismail
  • 117
  • 2
  • 12
  • I have the same issue and unfortunately was not able to solve it. But it the issue doesn't appear if deployed to firebase... – ashiaka Jul 05 '19 at 09:20
  • Actually, I forgot to specify the app bucket.. ````busboy.on("finish", () => { storage.bucket(config.storageBucket)```` see: [link](https://github.com/Ismail-Opatola/wur-react-firebase-cloud-functions/commit/23f0cdebe2f876b812e522a0af10d4c66ca8b935) @ashiaka – Ismail Jul 06 '19 at 13:09

0 Answers0