I'm writing code on image upload function to google cloud. I'm able to upload image to gcloud but not able resize it before uploading. I tried with node js sharp library to resize but not able to implement it properly. Here is my code below:
My Upload function
const processFile = require('../middleware/upload')
const { format } = require('util')
const { Storage } = require('@google-cloud/storage')
// Instantiate a storage client with credentials
const storage = new Storage({ keyFilename: 'xxxxx.json' })
const bucket = storage.bucket('<---bucket name--->')
const upload = async (req, res) => {
try {
await processFile(req, res)
if (!req.file) {
return res.status(400).send({ message: 'Please upload a file!' })
}
// Create a new blob in the bucket and upload the file data.
const blob = bucket.file(req.file.originalname.replace(/ /g, "_"))
const blobStream = blob.createWriteStream({
resumable: false,
})
blobStream.on('error', (err) => {
res.status(500).send({ message: err.message })
})
blobStream.on('finish', async (data) => {
// Create URL for directly file access via HTTP.
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`,
)
try {
// Make the file public
await bucket.file(req.file.originalname).makePublic()
} catch {
return res.status(500).send({
message: `Uploaded the file successfully: ${req.file.originalname}, but public access is denied!`,
url: publicUrl,
})
}
res.status(200).send({
message: 'Uploaded the file successfully: ' + req.file.originalname,
url: publicUrl,
})
})
blobStream.end(req.file.buffer)
} catch (err) {
if (err.code == "LIMIT_FILE_SIZE") {
return res.status(500).send({
message: "File size cannot be larger than 2MB!",
});
}
res.status(500).send({
message: `Could not upload the file: ${req.file.originalname}. ${err}`,
})
}
}
module.exports = {
upload
}
My Multer lib
const processFile = require('../middleware/upload')
const util = require("util");
const Multer = require("multer");
const maxSize = 2 * 1024 * 1024;
let processFile = Multer({
storage: Multer.memoryStorage(),
limits: { fileSize: maxSize },
}).single("file");
let processFileMiddleware = util.promisify(processFile);
module.exports = processFileMiddleware;
The above code is able to push image to gcloud. Can someone please suggest how to resize it with node js sharp and upload to gcloud. Thank you in advance