1

I am using Google-Cloud-Storage. This code will save an object in the bucket but it is just empty. It shows a size of 0 Bytes

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);
Edwin Rodriguez
  • 153
  • 1
  • 4
  • 11
  • 1
    How confident are you that req.files.file.buffer contains anything? Maybe try a trivial sample where you just write a constant string. – Kolban Jun 03 '20 at 18:13
  • thanks Kolban, that was it. I needed to return req.files.file.data which contained the buffer. – Edwin Rodriguez Jun 03 '20 at 18:25

1 Answers1

7

Working through the comments, it was found that the issue was that the write to GCS wasn't being passed the expected data which resulted in nothing being written. In the original code, we had:

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

which would have closed the file after writing the data in the variable. However, the variable's identity wasn't correct and what should have been coded was:

stream.end(req.files.file.data);
Kolban
  • 13,794
  • 3
  • 38
  • 60