'How to send pictures from React-Native app to the Django server using Expo ImagePicker?

I study React Native and Django and create an iOS app, which recognize text in pictures. I need to upload images to the Django Server but I have error from server:

[26/Apr/2022 12:10:51] "POST /api/textocr/ HTTP/1.1" 400 519
error {'title': [ErrorDetail(string='Обязательное поле.', code='required')], 'image': [ErrorDetail(string='Расширение файлов “” не поддерживается. Разрешенные расширения: bmp, dib, gif
, tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2
c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm.', code='invalid_extension')]}
Bad Request: /api/textocr/

What I did:

Django Server:

models.py

from django.db import models

# Create your models here.

class Ocr(models.Model):
    title = models.CharField(max_length=100, blank=False, null=False)
    image = models.ImageField(upload_to='images/', null=True, blank=True)

    def __str__(self):
        return self.title

serializers.py:

from rest_framework import serializers
from .models import Ocr

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ocr
        fields = '__all__'

views.py:

from django.shortcuts import render
from .serializers import PostSerializer
from .models import Ocr
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status
# Create your views here.

from django.http.response import JsonResponse
# Create your views here.

# import pytesseract to convert text in image to string
import pytesseract
# import summarize to summarize the ocred text

from .forms import ImageUpload
import os

# import Image from PIL to read image
from PIL import Image

from django.conf import settings

# Create your views here.

class PostView(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def get(self, request, *args, **kwargs):
        posts = Ocr.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)

    def post(self, request, *args, **kwargs):
        posts_serializer = PostSerializer(data=request.data)
        if posts_serializer.is_valid():
            posts_serializer.save()
            return Response(posts_serializer.data, status=status.HTTP_201_CREATED)
        else:
            print('error', posts_serializer.errors)
            return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

React-Native: CameraScreen.js:

const [image, setImage] = useState(null);

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result.uri);

    if (!result.cancelled) {
      postToServer(result)
      setImage(result);
    }
    
  };

  const postToServer = (img) => {
    const formData = new FormData();
    
    formData.append('image', {
                uri: img.uri,
                type: 'image/jpg', // or photo.type
                name: 'testPhotoName'
            });
        
        fetch('http://192.168.0.149:8000/api/textocr/', {
          method: 'POST',
          body: formData,
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
          }
        });
    }

When I pick an image from iPhone app display uri in the console:

file:///var/mobile/Containers/Data/Application/11E48F15-B1F7-4125-BCCA-0A173B3F5A49/Library/Caches/ExponentExperienceData/%2540anonymous%252Flive-text-81fcee79-3393-4551-a482-a5fa88d9f178/ImagePicker/03C5355A-E685-43B0-B836-B2D620E42E60.jpg


Sources

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

Source: Stack Overflow

Solution Source