Upload a file without a model in django or django rest framework

Uploading a file is a very common requirement. We have two model fields in django to upload files as well. For images, you can use ImageField as shown below:


profile_image = models.ImageField(upload_to='user_profile/') 

upload_to defines the directory where images should reside. By default, django will automatically create this directory inside the media directory when you upload an image.

Similarly, for files like documents/videos/audio etc., you can use FileField


document = models.FileField(upload_to='uploads/')

 

As soon as you upload a document, django will create a directory “uploads” under the directory path set in MEDIA_ROOT. You can set MEDIA_ROOT in settings.py file as shown below:


MEDIA_ROOT = os.path.join(BASE_DIR, "media")

MEDIA_URL =  '/media/'

 

Sometimes, it is required that we don’t have any model and want to upload the file without creating a ImageFiled or FileField. Here is how you can upload the file.


from core.settings import MEDIA_ROOT

class UploadFile(APIView):
   """
   file upload
   """

   def post(self, request, *args, **kwargs):
       try:
           file_object = request.FILES['document']
           file_name = file_object.name
           print("file_name", file_name)
           print("content_type", file_object.content_type)
           print("size", file_object.size)

           with open(MEDIA_ROOT + "/" + file_name, 'wb+') as f:
               for chunk in file_object.chunks():
                   f.write(chunk)                 
           return Response({"data": {"file_name":file_name}})

       except Exception as e:
           print(str(e))
           responseData = {'message': str(e), 'status': False}
           return Response(responseData)

 

add your view in urls.py


url(r'^v1/upload-test/$', views.UploadFile.as_view(), name='upload-test'),

 

Postman Request

postman request

 

Uploaded file in /media directory

uploaded-file

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares