Skip to main content

Command Palette

Search for a command to run...

Multiple File Upload With One Request In Django Rest Framework

Updated
3 min read
Multiple File Upload With One Request In Django Rest Framework
O

I’m a passionate, detail-oriented and product-minded Software Engineer, I’ve 5+ years of experience in programming, building web and mobile apps to scale. I'm a Developer Advocate who's always willing to help and assist anyone venturing into the tech world.

Most times, we might want to upload multiple files to our server in a single request. In this tutorial I'll be uploading multiple files and then returning the image URL as response. I assume we already know how to install and setup django, django rest framework and configure media URL for handling media files.

So, lets begin

Step 1

First of all, we start with the model class.

from django.db import models

class FileUpload(models.Model):
    name = models.CharField(max_length=20) 
    file = models.FileField() 
    def __str__(self):
        return self.name

We'll be creating two fields here; one is the name field to store what ever we want , the other one is the file field to upload files.

Step 2

Next, we'll create the serializer class to receive the request and to display data from database.

from rest_framework import serializers
from index.models import FileUpload

class FileUploadSerializer(serializers.ModelSerializer):        
    file = serializers.ListField(
        child=serializers.FileField(max_length=100000,
        allow_empty_file=False,
        use_url=False ))

    class Meta:
        model = FileUpload
        fields = '__all__'

    def create(self, validated_data):
        name=validated_data['name']
        file=validated_data.pop('file')   
        image_list = []     
        for img in file:
            photo=FileUpload.objects.create(file=img,name=name)
            imageurl = f'{photo.file.url}'
            image_list.append(imageurl)        
        return image_list


class FileUploadDisplaySerializer(serializers.ModelSerializer):        
    class Meta:
        model = FileUpload
        fields = '__all__'

We'll be using two serializer class here, one is to actually receive multiple image from the request so that we can save, the other one is to display the data from the database. We can't do them in one serializer because the first one is meant to receive list of data files to be uploaded.

In the create method, we get the 'name' field and the 'file' field, we used ".pop" to get the file values to upload and then loop through it and save everything in the database. And then appending the URL for the saved image in a list to be returned back as a response.

Step 3

We'll be setting up the views to be able to receive the request, in this tutorial, I'll be going with class based views.

from index.models import FileUpload #import the model
from index.serializers import FileUploadDisplaySerializer, FileUploadSerializer #import the serializer
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework import status 

class FileUploadView(generics.ListCreateAPIView):
    permission_classes = [AllowAny]
    serializer_class = FileUploadDisplaySerializer
    def post(self, request, format=None): 
        serializer = FileUploadSerializer(data=request.data)
        if serializer.is_valid():    #validate the serialized data to make sure its valid       
            qs = serializer.save()                     
            message = {'detail':qs, 'status':True}
            return Response(message, status=status.HTTP_201_CREATED)
        else: #if the serialzed data is not valid, return erro response
            data = {"detail":serializer.errors, 'status':False}            
            return Response(data, status=status.HTTP_400_BAD_REQUEST)
    def get_queryset(self):
        return FileUpload.objects.all()

Step 4

In the final step, we will be setting the URL and connecting it to the views class.

from django.urls import  path

from index.views import FileUploadView

urlpatterns = [
    path('', FileUploadView.as_view(), name='file-upload'),

]

Volla! everything is done, you can now test the URL endpoint to upload multiple files in one request.

Screenshot from 2022-05-06 16-47-59 (1).png

For this test I'm using thunder client for VS Code, a light weight package for running http requests. From the request, we can see that we uploaded three images with the field name as 'file' and the name as well. We can see from the response, we get the URL of the image uploaded back.

CONCLUSION

With this knowledge, we can choose to send list of multiple images in one request, it does not just end there, we can also choose to upload list of other items (strings, intergers, objects etc.) to the server in one request.

You can check out the code at:

https://github.com/budescode/django-multiple-file-upload.git

E

what about returning id when sending post method? Thanks in advance :)

M

Very informative, thanks

From where url comes from in:

imageurl = f'{photo.file.url}'

?

O

It’s django inbuilt method to return the url of the file saved. You can see it from the response gotten.

2
M

Omonbude Emmanuel, it's nice, thank you for the explanation.

E

You did well

O

Thank you