How to send an image file through xhr request to fastapi?

by tressie.damore , in category: Javascript , 4 months ago

How to send an image file through xhr request to fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 4 months ago

@tressie.damore 

To send an image file through an XHR request to FastAPI, you can do the following:

  1. Create a form in your HTML file with an input field of type file for the user to select the image file.
1
2
3
4
<form id="imageForm">
  <input type="file" name="image" id="imageInput">
  <button type="submit">Upload Image</button>
</form>


  1. Add a JavaScript code that listens to the form submission event, collects the selected image file, and sends it as a FormData object in an XHR request.
 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. In your FastAPI server, define a POST endpoint that receives the image file and saves it.
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.

Related Threads:

How to send a base64 encoded image to a fastapi backend?
How to request multiple file in fastapi?
How to validate request body in fastapi?
How to update request parameters in fastapi?
How to read non json data from request in fastapi?
How to restrict content-type in fastapi request header?