使用Node上传图像的进度状态以及如何将状态事件推送到Fronthend

时间:2019-06-24 09:53:32

标签: node.js amazon-s3 progress-bar

想在S3上上传文件,并且需要获取进度状态并将进度数据发送到UI。

嗨极客,

我正在使用Node Js在S3上上传文件,我还希望将进度状态发送到UI以填充进度栏。但是我无法获得正确的状态,而是每次都获得相同的进度数据,并且无法将数据发送到UI

function UploadMultiple(req, res, next) {
  const s3 = new AWS.S3({
    accessKeyId: 'AKIAIU7MBIZKRXF7ISMQ',
    secretAccessKey: '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'
  });
  const data = req.body;
  if (!data.imageUrl) {
    return next('wro');
  }
  // if (!(isBase64(data.imageUrl, { mime: true }))) {
  //   const error = getError(httpStatusCode.BAD_REQUEST, responseMessage.INVALID_IMAGE_FORMAT);
  //   deferred.reject(error);
  //   return deferred.promise;
  // }
  const buf = Buffer.from(data.imageUrl.replace(/^data:image\/\w+;base64,/, ''), 'base64');
  const type = data.imageUrl.split(';')[0].split('/')[1];
  const s3Data = {
    Bucket: `loyal-zoom-staging/${data.folder}`,
    Key: `${data.id}.${type}`,
    Body: buf,
    ContentEncoding: 'base64',
    ContentType: `image/${type}`
  };
  s3.putObject(s3Data).on('httpUploadProgress', function (progress) {
    console.log(progress.loaded + " of " + progress.total + " bytes");
    // res.send(progress.loaded + " of " + progress.total + " bytes");
  })
    .send((err, result) => {
      if (err) {
        // infoLog('Failed to save image in S3', null, null, null);
        return next(err);
      }
      data.imageUrl = `https://s3.ap-south-1.amazonaws.com/loyal-zoom-staging/${data.folder}/${data.id}.${type}`;
      // infoLog('Image Uploaded sucessfully on S3', null, null, null);
      console.log(result);
    });
}

28568个字节,共28568个字节 master.js:648 28568 of 28568字节

您能帮忙解决这个问题吗?

Node Js版本:8.10.0

0 个答案:

没有答案