'Uploading Image from local storage to API

Suppose I have an api that takes an image and does some processing. Example:

@app.post("/upload/")
async def upload_image(file: UploadFile = File(...)):
    file_content = await file.read()
    print(file_content)
    extension = file.filename.split(".")[1]
    if extension not in ["png", "jpg"]:
        return {"status": "error", "detail": "File is not supported"}
    ocr_result = ocr(file_content)
    return {"filename": file.filename, "text": ocr_result}

And I want to make a post request to this using axios by uploading an image from my local storage. So I did this:

let file = fs.createReadStream('discount.jpg')

let data = new FormData();
data.append('file', file, 'discount.jpg');
axios.post('http://127.0.0.1:8000/upload/', data, {
  headers: {
    'Content-Type': 'multipart/form-data' 
  }  
}).then(function() {
    console.log(response.data);
})

But this doesn't seem to be working. Any idea on what am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source