2

I am trying to send some data from the client side (react native) that includes a few images so I append them to formdata and successfully send it through a post request but I am having trouble figuring out how to handle it on the server side.

My react code:

const post = async () => {
    const token = await getToken();
    const [description, setDescription] = useState('');

    const formData = new FormData();

    images.forEach((image) => {
      formData.append(`images`, {
        uri: image,
        type: 'image/jpeg',
        name: image,
      });
    });
    formData.append('description', description);
    console.log('formdata:', formData);

    try {
      await axios.post(URL, formData._parts, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: token,
        },
      });
    } catch (e) {
      console.log(e);
    }
  };

when i console log formData._parts on client side i get:

formdata: [["images", {"name": "/Library/Developer/CoreSimulator/Devices/123.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/123.jpg"}], ["images", {"name": "/Library/Developer/CoreSimulator/Devices/456.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/456.jpg"}], ["description", "Test"]]

It post request only works whenn i send formData._parts but not when i send just formData

on my server side (django/drf):

models.py:

class Post(models.Model):
    user_id = models.ForeignKey(
        User, on_delete=models.CASCADE, default=None
    )
    images = models.FileField(
        max_length=3000, default=None, null=True, blank=True, upload_to='media/post_images')
    description = models.TextField(null=False, default=None)
    date = models.DateTimeField(editable=False, auto_now_add=True)

serializers.py:

class PostSerializer(serializers.ModelSerializer):
    images = serializers.FileField()

class Meta:
    model = Post
    fields = "__all__"

views.py

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

def post(self, request, format=None):

    form_data = request.data

    images = form_data.get('images')
    description = form_data.get('description')
    user_id = self.request.user

    print(form_data)

    post = Post.objects.create(
        images=images, description=description, user_id=user_id)

    post.save()

    serializer = PostSerializer(post)

    return Response(serializer.data, status=status.HTTP_201_CREATED)

when i print the form_data in python i get:

<QueryDict: {'0': ['images'], '1.uri': ['/Library/Developer/CoreSimulator/Devices/123.jpg'], '1.type': ['image/jpeg'], '1.name': ['/Library/Developer/CoreSimulator/Devices/123.jpg'], '1.0': ['images'], '1.1.uri': ['/Library/Developer/CoreSimulator/Devices/456.jpg'], '1.1.type': ['image/jpeg'], '1.1.name': ['/Library/Developer/CoreSimulator/Devices/456.jpg'], '2.0': ['description'], '2.1': ['Test']}>

How can i extract the data and save it to the database?

1
  • You should upload images data as either base64 or binary data Commented Jan 1, 2023 at 18:43

1 Answer 1

1

Django is handling that for you. You can try to access your images with:

request.FILES.getlist("images")

This will give you a list of all the images that are found in the submitted form.

EDIT:

For the Backend actually being able to read the data, it obviously also has to be send. To append the data you can use something like this:

var formData = new FormData();
formData.append('avatar', {uri: this.state.avatar.uri, name: 'yourname.jpg', type: 'image/jpg'});

let response = await fetch(url, {
   method: 'POST',
   headers: {
     'Accept': 'application/json',
     'Content-Type': 'multipart/form-data',
     'Authorization': ' Token '+accessToken,
   },
   body: formData
 });
Sign up to request clarification or add additional context in comments.

2 Comments

returns an empty list
yeah cause you are not sending the data lmao just saw that. You have to add a body. I will edit my answer to clarify

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.