I want to use this package: sharp - npm in beforeSaveFile trigger but it doesn’t work. beforeSaveFile doesn’t change anythink.
My codes:
Parse.Cloud.define('test', async (req) => {
try {
const Resim = Parse.Object.extend('Resim')
const obj = new Resim()
const { photo } = req.params
let uploadedFile = await new Parse.File(
'galleryFile',
{ base64: photo },
'image/png'
)
obj.set('photo', uploadedFile)
const data = await obj.save()
return data
} catch (error) {
throw error
}
})
Parse.Cloud.beforeSaveFile(async (req) => {
const image = await sharp(req.file).resize(256)
return image
})
Thanks for help.
2 Likes
Try this
const file = req.file;
const fileData = await file.getData();
const imageBuffer = Buffer.from(fileData, 'base64');
const newImageBuffer = await sharp(imageBuffer).resize(256).toBuffer();
return new Parse.File("image", { base64: newImageBuffer.toString('base64')});
2 Likes
It works thank you so much !
Now i have different questions. I want to send file like this: (Not base64 normal file)
let uploadedFile = await new Parse.File(
‘galleryFile’,
photo,
‘image/png’
)
And i want to implement this:
.webp({lossless:true, quality: 60, alphaQuality: 80, force: false})
This is my code:
const file = req.file;
const fileData = await file.getData();
const imageBuffer = Buffer.from(fileData, 'base64'); // I'll send image not base64
const newImageBuffer = await sharp(imageBuffer).resize(600,600).webp({lossless:true, quality: 60, alphaQuality: 80, force: false}).toBuffer();
return new Parse.File("image", { base64: newImageBuffer.toString('base64')}, 'image/webp');
what do you mean by
I’ll send image not base64
Do you want to change file in trigger or you want this when you upload new file?
But either way you have to convert file to either base64 or byte array. These are two objects that parse file accepts. In my opinion, base64 is much easier to work with.
If you want to upload file from disk, then you can do this by:
const fileBase64 = fs.readFileSync("/path/to/file.png").toString('base64');
const file = new Parse.File("fileName", { base64: fileBase64 });
await file.save();
1 Like