Reputation: 127
I'm trying to upload a base64 jpeg image to Firebase Storage I don't know what's wrong. I don't think the error is from my image encoding. I'm trying to upload an image from the user's phone to the firebase storage using React Native (fetch API) to send the request.
index.js file:
const functions = require("firebase-functions");
const cors = require("cors")({ origin: true });
const fs = require("fs");
const UUID = require("uuid-v4");
const gcconfig = {
projectId: "awsome-34343434343434",
keyFileName: "awsome.json"
};
const { Storage } = require("@google-cloud/storage");
const storage = new Storage(gcconfig);
exports.storeImage = functions.https.onRequest((request, response) => {
cors(request, response, () => {
console.log("THE BODY:" + JSON.stringify(request.body));
const body = JSON.parse(request.body);
console.log("THE IMAGE:" + body.image);
fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err => {
console.log(err);
return response.status(500).json({ error: err });
});
const bucket = storage.bucket("awsome-1548769019561");
const uuid = UUID();
console.log("UUID: " + uuid);
bucket.upload(
"/tmp/uploaded-image.jpg",
{
uploadType: "media",
destination: "/places/" + uuid + ".jpg",
metadata: {
metadata: {
contentType: "image/jpeg",
firebaseStorageDownloadTokens: uuid
}
}
},
(err, file) => {
if (!err) {
response.status(201).json({
imageUrl:
"https://firebasestorage.googleapis.com/v0/b/" +
bucket.name +
"/o/" +
encodeURIComponent(file.name) +
"?alt=media&token=" +
uuid
});
} else {
console.log(err);
response.status(500).json({ error: err });
}
}
);
});
});
the request body I sent :
{"image": "/9j/4QG1RXhpZgAATU0AKgAAAAgABwEQA..."}
I get this error:
SyntaxError: Unexpected token o in JSON at position 1
at Object.parse (native)
at cors (/user_code/index.js:21:24)
at cors (/user_code/node_modules/cors/lib/index.js:188:7)
at /user_code/node_modules/cors/lib/index.js:224:17
at originCallback (/user_code/node_modules/cors/lib/index.js:214:15)
at /user_code/node_modules/cors/lib/index.js:219:13
at optionsCallback (/user_code/node_modules/cors/lib/index.js:199:9)
at corsMiddleware (/user_code/node_modules/cors/lib/index.js:204:7)
at exports.storeImage.functions.https.onRequest (/user_code/index.js:18:3)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)
Upvotes: 0
Views: 1033
Reputation: 5272
Your error is being caused by the line const body = JSON.parse(request.body);
Firebase automatically parses data from the request body, there's no need for you to try to do it yourself, see the section "Read values from the request" in the function calls docs. Since your body is already in JSON format, and your function is trying to re-JSON-ify it... then it triggers that error. Take out that line and you shouldn't get that error anymore.
Upvotes: 1