Last active
August 29, 2015 14:10
-
-
Save RobertKolner/62914524412ddf955c55 to your computer and use it in GitHub Desktop.
Basic generic django file upload function. Compatible with Froala Editor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.core.files.storage import default_storage | |
from django.http import HttpResponse | |
import json | |
import os | |
def upload_file(request): | |
if request.method.lower() != 'post': | |
return HttpResponse('Invalid method {}. Only POST allowed.'.format(request.method.upper()), status=405) | |
if not request.user or not request.user.is_authenticated(): | |
return HttpResponse('Forbidden', status=403) | |
if not request.FILES: | |
return HttpResponse('Invalid request', status=400) | |
urls = [] | |
for key, file_obj in request.FILES.items(): | |
urls.append(default_storage.save(os.path.join(settings.MEDIA_ROOT, file_obj.name), file_obj)) | |
urls = map(lambda url: default_storage.url(url), urls) | |
response = { | |
'link': urls if len(urls) > 1 else urls[0] if urls else None | |
} | |
return HttpResponse(json.dumps(response)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment