With the following code I resize and upload every new image to the storage bucket.
This works, as in the files are created and uploaded to storage I can see the correctly named files. BUT those files seem not to be able to previewed inside the console. (security?)
exports.generateThumbs = functions
.region("europe-west1")
.storage.object()
.onFinalize(async (object) => {
const bucket = admin.storage().bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split("/").pop();
const bucketDir = path.dirname(filePath);
const workingDir = path.join(os.tmpdir(), "resize");
const tmpFilePath = path.join(workingDir, "source.jpeg");
if (
fileName.includes("_resized_") ||
!object.contentType.includes("image")
) {
console.log("exiting function");
return false;
}
// 1. Ensure thumbnail dir exists
await fs.ensureDir(workingDir);
// 2. Download Source File
await bucket.file(filePath).download({
destination: tmpFilePath,
});
// 3. Resize the images and define an array of upload promises
const sizes = { thumb: 100, small: 350, medium: 1000 };
const uploadPromises = Object.keys(sizes).map(async (k) => {
const size = sizes[k];
const imgName = `${fileName}_resized_${k}`;
const thumbPath = path.join(workingDir, imgName);
// Resize source image
await sharp(tmpFilePath)
.resize(size, size, { fit: "inside", withoutEnlargement: true })
.toFile(thumbPath);
// Upload to GCS
return bucket.upload(thumbPath, {
destination: path.join(bucketDir, imgName),
uploadType: "media",
metadata: {
contentType: object.contentType,
},
});
});
// 4. Run the upload operations
await Promise.all(uploadPromises);
// 5. Cleanup remove the tmp/thumbs from the filesystem
return fs.remove(workingDir);
});
original uploaded file can be previewed
the files generated by the function can not be previewed
I have no clue what is going on, and I can not seem to fix it after hours of trying.
Anyone has an idea why these files are uploaded, have a file size, have the correct name (_thumb, _medium, etc..) but can not be viewed inside the console.
Thank you for any feedback,
Matthias