React + Django Rest Framework – Multiple File Upload
Uploading multiple files in a React and Django Rest Framework (DRF) application can be achieved with a few simple steps. In this article, we will explore how to create a file upload feature using these technologies.
Setting up the backend with Django Rest Framework
First, let’s set up the backend with Django Rest Framework. You will need to create a new Django project and app if you haven’t already. Then, install Django Rest Framework by running the following command in your terminal:
pip install djangorestframework
Create a new model to store the files and their metadata. Here’s an example model:
from django.db import models
class File(models.Model):
title = models.CharField(max_length=100)
file = models.FileField(upload_to='uploads/')
Next, create a serializer for the File model:
from rest_framework import serializers
from .models import File
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
fields = '__all__'
Create a view to handle the file uploads:
from rest_framework import viewsets
from .models import File
from .serializers import FileSerializer
class FileViewSet(viewsets.ModelViewSet):
queryset = File.objects.all()
serializer_class = FileSerializer
Finally, set up the URL routing for the file uploads:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import FileViewSet
router = DefaultRouter()
router.register(r'files', FileViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Creating the React front end
Now that the backend is set up, let’s create the React front end to handle the file uploads. Start by creating a new React project if you haven’t already:
npx create-react-app file-upload-app
Next, create a file upload component in React. You can use the HTML input element with the multiple attribute to allow users to select multiple files:
import React, { useState } from 'react';
const FileUpload = () => {
const [files, setFiles] = useState(null);
const handleFileChange = (e) => {
setFiles(e.target.files);
}
const handleFileUpload = () => {
const formData = new FormData();
for (let i = 0; i
<input type="file" multiple onChange={handleFileChange} />
<button onClick={handleFileUpload}>Upload Files</button>
</div>
);
}
export default FileUpload;
Once the files are selected and the upload button is clicked, a POST request should be made to the Django Rest Framework backend to upload the files. You can use the Fetch API or a library like Axios to make the POST request.
Conclusion
With React and Django Rest Framework, it is straightforward to create a file upload feature that allows users to upload multiple files. By following the steps outlined in this article, you can easily implement the file upload functionality in your web application.