I am trying to create some code which uploads a screenshot from pupeteer to a fastapi endpoint. The endpoint currently looks like:
@nodes_router.post("/node/{node_name}/screenshot")
async def set_node_screenshot(node_name: str, screenshot: UploadFile = File(...)):
screenshot_path = screenshot_folder / f"{node_name}.jpg" # Save as .jpg
# Reset the file pointer after reading for logging
screenshot.file.seek(0)
try:
# Save the uploaded .jpg file
with screenshot_path.open("wb") as buffer:
shutil.copyfileobj(screenshot.file, buffer)
return {"message": "Screenshot uploaded successfully"}
except Exception as e:
return {"error": f"Error uploading screenshot: {str(e)}"}
And the javascript side looks like:
async function uploadScreenshot(nodeName, page) {
try {
// Define the path where the screenshot will be saved (in jpg format)
const screenshotPath = path.join(__dirname, `screenshot.jpg`);
// Take the screenshot and save it as a .jpg file
await page.screenshot({ path: screenshotPath, type: "jpeg" }); // Save as JPEG
// Create a FormData instance
const formData = new FormData();
formData.append("screenshot", fs.createReadStream(screenshotPath), {
filename: `${nodeName}.jpg`, // Ensure the filename is passed
contentType: "image/jpeg", // Set the correct content type
});
const screenshotUrl = `http://localhost:5000/node/${nodeName}/screenshot`;
// Perform the upload using fetch
const response = await fetch(screenshotUrl, {
method: "POST",
body: formData,
headers: formData.getHeaders(),
});
if (response.ok) {
console.log("Upload successful");
} else {
const text = await response.text();
console.error("Error uploading file:", response.statusText, text);
}
} catch (error) {
console.error("Error uploading screenshot:", error);
}
}
// code to get a page with puppeteer...
const pages = await browser.pages();
const page = pages[0];
await uploadScreenshot("foo", page);
however it is saying:
Error uploading file: Bad Request {"detail":"There was an error parsing the body"}
When I look on the server logs of fastapi it says:
Expected boundary character 45, got 91 at index 2
INFO: 127.0.0.1:58121 - "POST /node/2b76e38a-7585-4fbe-b777-d846d30f0aa8/screenshot HTTP/1.1" 400 Bad Request
if I remove the headers: formData.getHeaders(),
code, it doesnt have the Expected boundary character error, but it says it is an unprocessable entity:
Error uploading file: Unprocessable Entity {"detail":[{"type":"missing","loc":["body","screenshot"],"msg":"Field required","input":null}]}
Why is this happening and how can I fix it?