[Fixed]-How To Upload File with Django Rest APi

25👍

First of all you need to define a parser in your view. This is because the API needs to know which headers to look for. Browsers transfer files as form-data, so you need to use the MultiPartParser and FormParser together. You can also use the FileUploadParser but you need to make sure your client is sending the correct HTTP headers.

from rest_framework.parsers import MultiPartParser, FormParser

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

Then, in the post method, your file will be present in the FILES QueryDict:

def post(self, request, format=None):
    my_file = request.FILES['file_field_name']
    filename = '/tmp/myfile'
    with open(filename, 'wb+') as temp_file:
        for chunk in my_file.chunks():
            temp_file.write(chunk)

    my_saved_file = open(filename) #there you go

0👍

Write your models like this:

from django.db import models
class PicModel(models.Model):
    file_to_be_uploaded = models.FileField(upload_to='/directory/where/you/what/to/upload/to')

if you uploading images then ImageField but install pillow by pip install pillow.

In you serializers.py assuming you are using rest_framework:

from rest_framework import serializers
from app_name.models import PicModel

class PicSerializer(serializers.ModelSerializer):
    class Meta:
        model = PicModel
        fields = '__all__' #or any way you may like to display you fields

In you views.py include assuming you are to using class-base views:

from app_name.models import PicModel
from app_name.serializers import PicModelSerializer
#other necessary imports

class PicList(APIView):
    def post(self, request, format=None):#or format can be json or api
        serializer = PicModelSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            ............more code

To test in json data write like:

{
    "file_to_be_uploaded":"//path//to//file//on//local//machine"
}
👤Aula

Leave a comment