Как загрузить скриншот из puppeteer в FastAPI?Python

Программы на Python
Ответить
Anonymous
 Как загрузить скриншот из puppeteer в FastAPI?

Сообщение Anonymous »

Я пытаюсь создать код, который загружает снимок экрана из puppeteer в конечную точку FastAPI. Конечная точка на данный момент выглядит так:

Код: Выделить всё

@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)}"}
А сторона javascript выглядит так:

Код: Выделить всё

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);
как там сказано:

Код: Выделить всё

Error uploading file: Bad Request {"detail":"There was an error parsing the body"}
Когда я смотрю журналы сервера fastapi, он говорит:

Код: Выделить всё

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
если я удалю заголовки: код formData.getHeaders(),, в нем не будет ошибки ожидаемого символа границы, но будет написано, что это необрабатываемый объект:

Код: Выделить всё

Error uploading file: Unprocessable Entity {"detail":[{"type":"missing","loc":["body","screenshot"],"msg":"Field required","input":null}]}
Почему это происходит и как это исправить?

Подробнее здесь: https://stackoverflow.com/questions/791 ... to-fastapi
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»