@tressie.damore
To send an image file through an XHR request to FastAPI, you can do the following:
1 2 3 4 |
<form id="imageForm"> <input type="file" name="image" id="imageInput"> <button type="submit">Upload Image</button> </form> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
document.getElementById("imageForm").addEventListener("submit", function(event) {
event.preventDefault();
var formData = new FormData();
var imageFile = document.getElementById("imageInput").files[0];
formData.append("image", imageFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/upload-image", true);
xhr.onload = function () {
if (xhr.status == 200) {
console.log("Image uploaded successfully");
}
};
xhr.send(formData);
});
|
1 2 3 4 5 6 7 8 9 |
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post("/upload-image")
async def upload_image(image: UploadFile = File(...)):
with open(f"uploaded_images/{image.filename}", "wb") as image_file:
shutil.copyfileobj(image.file, image_file)
return {"message": "Image uploaded successfully"}
|
With these steps, you can send an image file through an XHR request to FastAPI and perform any required processing on the server-side.