How to send a JSON file containing a HTML created image

I am working with my first react based application and am attempting to send an image to my Flask based server but it is saying that the image is not being attached. The basis is to take a live image and then send it to an AI model in order to process the image and I have found success with uploading a file straight, but not with live videos.

This is the main file I am having issues with

"use client";
import "./myscript.css"
import { useEffect, useRef } from 'react';

const MyWebcam = () => {
    const videoRef = useRef(null);


  useEffect(() => {
    const getUserMedia = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          videoRef.current.addEventListener('loadedmetadata', () => {})
        }
      } catch (error) {
        console.error(error);
      }
    };

    getUserMedia();

  }, []);

  const takePicture = async () => {
    if (!videoRef.current || !videoRef.current.videoWidth || !videoRef.current.videoHeight) {
        console.log(videoRef.current)
        console.error('Video not ready');
    }
    else{
      const canvas = document.createElement('canvas');
      canvas.width = videoRef.current.videoWidth;
      canvas.height = videoRef.current.videoHeight;
      const context = canvas.getContext('2d');
      context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
      const imgUrl = canvas.toDataURL('image/png');
      const img= document.getElementById("picture")
      img.src = imgUrl

      let data = context.getImageData(0, 0, canvas.width, canvas.height)
      const formData = new FormData()
      formData.append('file', data.data)
      console.log("pre JSON fetching")
      console.log(formData)
  try {
    const response = await fetch("http://localhost:8080/results", {
      method: 'POST',
      body: formData
    });
    console.log(response)
    const data = await response.json();
    console.log('Response:', data);
    let ex =  document.getElementById("translation")
    ex.textContent = data.message
      }
  catch(error){
      console.error(error)        }



    }
    
  }

  return (
<div className="fullscreen-container">
  <div className="input-div">
    <h2>Video Capture</h2>
    <div className="video-container">
      <video ref={videoRef} autoPlay width="900" height="900" />
      <div className="image-container">
        <img id="picture" width="900" height="900" alt="Captured" />
      </div>
    </div>
    <button type="button" onClick={takePicture}>Take Picture</button>
    <p id="translation">Translation</p>
  </div>
</div>



  );
};

export default MyWebcam;

This is the server I am trying to send to

from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
from model import ASLModel
import torch
from pathlib import Path
from torchvision import transforms, datasets
from PIL import Image


'Access-Control-Allow-Origin: *'


#app instance
app = Flask('__name__')
CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'



@app.route("/results", methods=["POST", "GET"])
@cross_origin()
def results():
    if 'file' not in request.files:
        print(request.files)
        return jsonify({'error': 'no file found'})
    print(request.files)
    img = request.files['file']

    trainData = datasets.ImageFolder(root="archive/asl_alphabet_train")
    classNames=trainData.classes
    device = "cpu"
    MODEL_PATH = Path("models")
    MODEL_PATH.mkdir(parents=True, exist_ok=True)
    MODEL_NAME = "ASL_CNN_MODEL.pth"
    MODEL_SAVE_PATH = MODEL_PATH / MODEL_NAME


    LoadedModel = ASLModel(input_shape=3, hidden_units=30, output_shapes=29)
    LoadedModel.load_state_dict(torch.load(MODEL_SAVE_PATH), False)
    LoadedModel.to(device=device)
    transform=transforms.Compose([transforms.Resize(size=(500, 500)), transforms.ToTensor()])
    LoadedModel.eval()

    img = Image.open(img)
    img.show()
    img = transform(img)    
    
    sample = torch.unsqueeze(img, dim=0).to(device)

    predLogit = LoadedModel(sample)

    result = torch.softmax(predLogit.squeeze(), dim=0)
    result = result.argmax()
    
    print("result", classNames[int(result)])
    
    response = jsonify({'message': classNames[int(result)]})
    return response



if __name__ == "__main__":
    app.run(debug=True, port=8080)#port 5000 has issues with requests

And this is the file for the page that lets you upload an image

'use client'
import './upload.css'

const MyInput = () => {
    var img
    const ImageUploaded = () => {
            let input = document.getElementById("file") //Get image
                img = input.files[0]
                let final= document.getElementById("picture") //access displayed tag for image
                final.src = URL.createObjectURL(img)
            
    }


    const SendToModel = async () => {
        // fetch("http://localhost:8080/results").then(
        //     response => response.json()).then(
        //         data => {
                    
        //             let ex =  document.getElementById("translation")
        //             ex.textContent = data.message
        //         }
        //     )


            const formData = new FormData()
            formData.append('file', img)
            console.log("pre JSON fetching")
            console.log(formData)
        try {
        const response = await fetch("http://localhost:8080/results", {
            method: 'POST',
            body: formData
        });
        console.log(response)
        const data = await response.json();
        console.log('Response:', data);
        let ex =  document.getElementById("translation")
        ex.textContent = data.message
            }
        catch(error){
            console.error(error)        }
    }


return (        


<div className="fullscreen-container">
<div className="input-div">
    <h2>Upload Images</h2>
    <p>Drag and drop images here or <span className="browse">browse</span></p>
    <input type="file" id="file" onChange={ImageUploaded} />
    <img id="picture" alt="Uploaded" />
    <button id="submit" onClick={SendToModel}>Submit</button>
    <p id="translation">Translation</p>
</div>
</div>
)}
export default MyInput

Any and all help would be appreciated because the “if file not in request.files” statement only gets hit when I try to send the live image

I looked your code cafully and found an issue. You tried to get image data from canvas with getImageData and send the content as a file to Flask server. But in this case, Flask server will not recognize the data as a file because it doesn’t support the format. To solve the issue, you need to convert canvas image into a Blob or a File, which will allow you to send it as an actual file.

I provde updated code:

In frontend side, update takePicture function:

const takePicture = async () => {
  if (!videoRef.current || !videoRef.current.videoWidth || !videoRef.current.videoHeight) {
    console.log(videoRef.current)
    console.error('Video not ready');
  } else {
    const canvas = document.createElement('canvas');
    canvas.width = videoRef.current.videoWidth;
    canvas.height = videoRef.current.videoHeight;
    const context = canvas.getContext('2d');
    context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);

    // Convert the canvas to a Blob
    canvas.toBlob(async (blob) => {
      const formData = new FormData();
      formData.append('file', blob, 'image.png'); // Add the Blob to the FormData

      try {
        const response = await fetch("http://localhost:8080/results", {
          method: 'POST',
          body: formData
        });
        const data = await response.json();
        console.log('Response:', data);
        let ex = document.getElementById("translation");
        ex.textContent = data.message;
      } catch (error) {
        console.error(error);
      }
    }, 'image/png');
  }
};

Hope it helps you.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật