How can I upload text file on Google drive using CloudFunctions?
File has been created on local folder but not sure how can I pass this in metadata body.
I have followed below approach:
Step 1: Write file
// Write file
fs.writeFileSync("sample.txt", "Hello content!");
Step 2: Prepare metadata
const metadata = {
name: "sample.txt",
parents: [parentFolder],
mimeType: "text/plain",
uploadType: "media",
};
Step 3: Call Google drive API to upload file
axios({
method: "POST",
url: "https://www.googleapis.com/drive/v3/files?supportsAllDrives=true",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
},
data: metadata,
})
.then((res) => {
response.status(200).send(res.data);
})
.catch((err) => {
response.status(500).send(err.message);
});
So whole function code is:
exports.onCreateFile = functions.https.onRequest((request, response) => {
// <-- Some validation -->
const parentFolder = request.query.parentFolder;
if (!parentFolder) {
response.status(400).send("Parent folder not found");
return;
}
// Write file
fs.writeFileSync("vault.txt", "Hello content!");
const metadata = {
name: "vault.txt",
parents: [parentFolder],
mimeType: "text/plain",
uploadType: "media",
};
axios({
method: "POST",
url: "https://www.googleapis.com/drive/v3/files?supportsAllDrives=true",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
},
data: metadata,
})
.then((res) => {
// console.log(res.data);
response.status(200).send(res.data);
})
.catch((err) => {
// console.log(err);
response.status(500).send(err.message);
});
});
Basically Mobile app will call CloudFunction by passing accessToken and parentFolderId and cloudFunction will upload file after some business logic.