Edwin Rodriguez
Edwin Rodriguez

Reputation: 163

Google cloud storage uploads 0 Bytes Node.js

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

Upvotes: 1

Views: 2181

Answers (1)

Kolban
Kolban

Reputation: 15266

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

Upvotes: 7

Related Questions