Upload image from Flutter to Python API as a body

74 Views Asked by At

I have an API in Python where it asks for uploading an image file in the request body, the API searches in a database for this image and analyze it.

Now I want to write the client side code for this using flutter. When I upload an image using imagePicker.gallary, the response works well and gives back the desired result, but when I upload it using camera the response body is empty.

Here is some of the code:

Flutter:
for the request part I use multipart request

final bytes = File(image.path).readAsBytesSync();

http.MultipartRequest request = http.MultipartRequest('POST',
    Uri.parse("url"));

request.files.add(
  await http.MultipartFile.fromPath(
    'file',
    image.path,
    contentType: MediaType('application', 'jpg'),
  ),
);

for picking the images I use flutter image_picker package

_picker.pickImage(source: ImageSource.camera);

And

_picker.pickImage(source: ImageSource.gallary);

Python:

class AGTImage(Image):
def __init__(self, image_contents: Union[bytes, str]) -> None:
    self.image_contents = image_contents

    def getMetadata(self, filename: str = "img.txt") -> dict:
    # Open image as PIL image
    pil_image = PILImage.open(io.BytesIO(self.image_contents))
    
    # Extract metadata from image
    metadata = {}
    exifdata = pil_image.getexif()
    for tagid in exifdata:
        tagname = TAGS.get(tagid)
        value = exifdata.get(tagid)
        metadata[tagname] = value
    
    # Add necessary fields to metadata
    if "Name" not in metadata:
        name = filename.split(".")[0].replace("_", " ")
        if " " in name:
            name = name.split(" ")[0] + " " + name.split(" ")[1]
        metadata["Name"] = name
    metadata["Name"] = str(metadata["Name"])
    if "Version" not in metadata:
        metadata["Version"] = str(b'0220')
    metadata["Version"] = str(metadata["Version"])
    if "DateTime" not in metadata:
        metadata["DateTime"] = datetime.datetime.now().strftime("%c")
    metadata["DateTime"] = str(metadata["DateTime"])
    if "Location" not in metadata:
        metadata["Location"] = "Not Defined"
    metadata["Location"] = str(metadata["Location"])

    return metadata
1

There are 1 best solutions below

0
Abdul Rehman On

Two things catch my eye, the content type you are setting as "application" "jpg", you can directly get the content type from image picker and use that:

String contentType = lookupMimeType(pickedFile.path) ?? 'application/octet- 
   stream';
   await http.MultipartFile.fromPath(
  'file',
   pickedFile.path,
   contentType: MediaType.parse(contentType),
    );

and it may not be relevant but try setting the image quality to 100:

 _picker.pickImage(
   source: ImageSource.camera,
   imageQuality: 100, 
     );