Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a file upload API using Django

I have a Django app that revolves around users uploading files, and I'm attempting to make an API. Basically, the idea is that a POST request can be sent (using curl for example) with the file to my app which would accept the data and handle it.

How can I tell Django to listen for and accept files this way? All of Django's file upload docs revolve around handling files uploaded from a form within Django, so I'm unsure of how to get files posted otherwise.

If I can provide any more info, I'd be happy to. Anything to get me started would be much appreciated.

like image 258
Mike Crittenden Avatar asked Jun 09 '11 21:06

Mike Crittenden


People also ask

How do I handle file upload in Django REST framework?

You just need to put the field in your ModelSerializer and set content-type=multipart/form-data; in your client. BUT as you know you can not send files in json format. (when content-type is set to application/json in your client). Unless you use Base64 format.

Does Python Django support multiple file upload?

The Django documentation for File Uploads, gives a brief understanding of the workflow of how to upload a single file using forms and importing in views. In a similar way, we can also tweak it to upload multiple files using forms and views.


1 Answers

Create a small view which accepts only POST and make sure it does not have CSRF protection:
forms.py

from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()

views.py

from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse, HttpResponseServerError

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

@csrf_exempt
@require_POST
def upload_file(request):            
    form = UploadFileForm(request.POST, request.FILES)
    if not form.is_valid():
        return HttpResponseServerError("Invalid call")
        
    handle_uploaded_file(request.FILES['file'])
    return HttpResponse('OK')

See also: Adding REST to Django

like image 92
Udi Avatar answered Sep 28 '22 05:09

Udi