Как исправить ошибку 'Часть прервана рано из-за неожиданного завершения многоэлементных данных' от busboy - PullRequest
0 голосов
/ 15 июня 2019

Я использую busboy для потоковой передачи изображения jpg на сервер узла. Но проблема заключается в том, что каждый раз, когда я пытаюсь загрузить файл с клиента с помощью Почтальона, происходит сбой со следующей ошибкой:

[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);
};

Я попытался добавить обработчик 'error' для файла в обработчик события 'file', а также в обработчик uploadImage

вот мой код:

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);
};

Запрос почтальона:

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--

Я ожидаю загрузки файла изображения в мое хранилище Firebase, вместо этого я получаю только метаданные файла

...