Here is the code of a method used in server:
export const insertImage = new ValidatedMethod({
name: 'images.insert',
validate: new SimpleSchema({
file: { type: String },
}).validator(),
run({ file }) {
Images.write(new Buffer(file, 'base64'), {
fileName: 'ImageName.png',
type: 'image/png',
}, function (error, fileRef) {
if (error) {
throw error;
} else {
console.log(`${fileRef.name} is successfully saved to FS. _id: ${fileRef._id}`);
return fileRef;
}
});
},
});
I am receiving file encode in base64 from frontend correctly.
The document is created in mongo database but the image saved in FS is corrupted.(it's not an image).
https://imgur.com/a/yCE2A
I am not able to receive fileRef, or information of saved document to client( frontend).
Well, I have fixed the first point using this hack: https://gist.github.com/madhums/e749dca107e26d72b64d
Now I am able to save image correctly. here my new Method.
export const insertImage = new ValidatedMethod({
name: 'images.insert',
validate: new SimpleSchema({
file: { type: String },
}).validator(),
run({ file }) {
Images.write(new Buffer(file.replace(/^data:image\/\w+;base64,/, ''), 'base64'), {
fileName: 'ImageName.png',
type: 'image/png',
}, (error, fileRef) => {
if (error) {
throw error;
} else {
console.log(`${fileRef.name} is successfully saved to FS. _id: ${fileRef._id}`);
return fileRef;
}
});
},
});
@badis I didn't get it. Have you solved it?
Yes, I solved the first part.
Now i need to return information to client.
I am not able to receive fileRef, or information of saved document to client( frontend). I am receiving undefined
Well, you can not return data to the same thread from async callback of async function.
Try to use .wrapAsync method or Future directly.
.wrapAsync sounds good ! because it's a meteor function.
Can you please help me implementing it with my code.
Images.write returns a FilesCollection instance. I want to return fileRef to my client.
Sure, you just wrapping it up, regardless what this function returns, as we interested in a callback of this function:
const asyncWrite = Meteor.wrapAsync(Images.write, Images);
// That's it
// Now when you need fileRef:
const fileRef = asyncWrite(buffer, opts);
Thank you !
Please, support this project by:
Most helpful comment
Thank you !