【问题标题】:Google cloud storage uploads 0 Bytes Node.js谷歌云存储上传 0 字节 Node.js
【发布时间】:2020-09-22 12:36:30
【问题描述】:

我正在使用 Google-Cloud-Storage。此代码将在存储桶中保存一个对象,但它只是空的。它显示的大小为 0 字节

req.file = req.files.file;
const bucketName = req.body.bucketName || DEFAULT_BUCKET_NAME;
const bucket = storage.bucket(bucketName);
const gcsFileName = `${Date.now()}-${req.file.name}`;
const file = bucket.file(gcsFileName);
const stream = file.createWriteStream({
  // resumable: false, 
  // gzip: true,
  metadata: {
      contentType: req.file.mimetype,
    },
});

stream.on('error', (err) => {
  req.file.cloudStorageError = err;
    next(err)
});
stream.on('finish', () => {
    console.log('image uploaded succesfully')
    req.file.cloudStorageObject = gcsFileName;
  return file.makePublic()
    .then(() => {
      req.file.gcsUrl = gcsHelpers.getPublicUrl(bucketName, gcsFileName);
      next()
    });
});

stream.end(req.files.file.buffer);

【问题讨论】:

  • 您对 req.files.file.buffer 包含任何内容的信心如何?也许尝试一个简单的示例,您只需编写一个常量字符串。
  • 感谢 Kolban,就是这样。我需要返回包含缓冲区的 req.files.file.data。

标签: node.js upload google-cloud-storage createwritestream


【解决方案1】:

通过 cmets 工作,发现问题在于对 GCS 的写入没有传递预期的数据,导致没有写入任何内容。在原始代码中,我们有:

stream.end(req.files.file.buffer);

在变量中写入数据后会关闭文件。但是,变量的标识不正确,应该编码的是:

stream.end(req.files.file.data);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2014-08-29
    • 2016-12-30
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多