Just starting out with cloud functions and figuring out how to upload an image from Flutter image_picker to cloud storage. Sharing the relevant cloud function code below:
// upload image to storage
const bucket = admin.storage().bucket();
const destination = data.storageCollection + '/' + data.itemID;
const filePath = data.filePath;
console.log('filePath is ' + data.filePath);
await bucket.upload(filePath, {
destination: destination,
gzip: true,
});
Encountering this error message:
Error in cloud function uploadProductPic: [firebase_functions/internal] project: undefined. Function: uploadImage. Error: ENOENT: no such file or directory, open '/data/user/0/com.appIdentifier.here/cache/a2b21481-ab56-4af5-bc97-4c2d050107e12579524263120800910.jpg'
Seems like I'm struggling with the correct storage directory path. Have tried various combinations without success:
'data/user/0/com.appIdentifier.here/cache/a2b21481-ab56-4af5-bc97-4c2d050107e12579524263120800910.jpg'
'cache/a2b21481-ab56-4af5-bc97-4c2d050107e12579524263120800910.jpg'
'/cache/a2b21481-ab56-4af5-bc97-4c2d050107e12579524263120800910.jpg'
Any ideas on where I might be going wrong with the file path? Currently using the .path property of an XFile.
Edit: Including my clientside code here:
Future<void> uploadProductPic(String productID, XFile file) async {
try {
await functions.httpsCallable('uploadImage').call(<String, String>{
"filePath": file.path,
"itemID": productID,
"storageCollection": "productPic",
"itemCollection": "products"
});
} catch (e) {error catching stuff}
And here's the complete cloud function:
/**
*
* @param {string} filePath
* @param {string} itemID
* @param {string} storageCollection
* @param {string} itemCollection
*/
exports.uploadImage = functions.region("australia-southeast1")
.https.onCall(async (data, context) => {
// Only allow authorised users to execute this function.
if (!(context.auth && context.auth.token)) {
throw new functions.https.HttpsError(
"permission-denied",
"Must be an administrative user to upload an image."
);
}
try {
// upload image to storage
const bucket = admin.storage().bucket();
const destination = data.storageCollection + '/' + data.itemID;
const filePath = data.filePath;
await bucket.upload(filePath, {
destination: destination,
gzip: true,
});
// get download url
const url = await bucket.getDownloadURL(destination);
// upload url to database
const firebaseRef = data.itemCollection + '/' + data.itemID;
await firebaseTools.firestore.updateDoc(firebaseRef, {'imageURL': url});
} catch (err) {
throw new functions.https.HttpsError("internal", "project: " +
process.env.GCP_PROJECT +
". Function: uploadImage. Error: " + String(err));
}
}
);
Appreciate any advice or guidance!