├── .gitignore ├── README.md ├── file_download ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py ├── urls.py └── views.py ├── file_project ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ └── settings.cpython-36.pyc ├── settings.py ├── urls.py └── wsgi.py ├── file_upload ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── migrations │ └── __init__.py ├── models.py ├── templates │ └── file_upload │ │ ├── ajax_upload_form.html │ │ ├── base.html │ │ ├── file_list.html │ │ └── upload_form.html ├── tests.py ├── urls.py └── views.py └── manage.py /.gitignore: -------------------------------------------------------------------------------- 1 | media/files/ 2 | __pycache__/ 3 | **/migrations 4 | *.sqlite3 5 | *.log 6 | *.temp 7 | .idea -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-file-upload-download 2 | Demo code examples for uploading and downloading files using Django, including setting storage directory, file renaming, Ajax upload and streaming of large files. 3 | -------------------------------------------------------------------------------- /file_download/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyunbo/django-file-upload-download/a2657faa263ae1d7168cbed8bce556597dc8a369/file_download/__init__.py -------------------------------------------------------------------------------- /file_download/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /file_download/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class FileDownloadConfig(AppConfig): 5 | name = 'file_download' 6 | -------------------------------------------------------------------------------- /file_download/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /file_download/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /file_download/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path, re_path 2 | from . import views 3 | 4 | # namespace 5 | app_name = 'file_download' 6 | 7 | urlpatterns = [ 8 | 9 | re_path(r'^download/(?P.*)/$', views.file_response_download, name='file_download'), 10 | 11 | ] 12 | -------------------------------------------------------------------------------- /file_download/views.py: -------------------------------------------------------------------------------- 1 | import os 2 | from django.http import HttpResponse, Http404, StreamingHttpResponse, FileResponse 3 | 4 | # Create your views here. 5 | # Case 1: simple file download, very bad 6 | # Reason 1: loading file to memory and consuming memory 7 | # Can download all files, including raw python .py codes 8 | 9 | 10 | def file_download(request, file_path): 11 | # do something... 12 | with open(file_path) as f: 13 | c = f.read() 14 | return HttpResponse(c) 15 | 16 | 17 | # Case 2 Use HttpResponse to download a small file 18 | # Good for txt, not suitable for big binary files 19 | def media_file_download(request, file_path): 20 | with open(file_path, 'rb') as f: 21 | try: 22 | response = HttpResponse(f) 23 | response['content_type'] = "application/octet-stream" 24 | response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) 25 | return response 26 | except Exception: 27 | raise Http404 28 | 29 | 30 | # Case 3 Use StreamingHttpResponse to download a large file 31 | # Good for streaming large binary files, ie. CSV files 32 | # Do not support python file "with" handle. Consumes response time 33 | def stream_http_download(request, file_path): 34 | try: 35 | response = StreamingHttpResponse(open(file_path, 'rb')) 36 | response['content_type'] = "application/octet-stream" 37 | response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) 38 | return response 39 | except Exception: 40 | raise Http404 41 | 42 | 43 | # Case 4 Use FileResponse to download a large file 44 | # It streams the file out in small chunks 45 | # It is a subclass of StreamingHttpResponse 46 | # Use @login_required to limit download to logined users 47 | def file_response_download1(request, file_path): 48 | try: 49 | response = FileResponse(open(file_path, 'rb')) 50 | response['content_type'] = "application/octet-stream" 51 | response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) 52 | return response 53 | except Exception: 54 | raise Http404 55 | 56 | 57 | # Case 5 Limit file download type - recommended 58 | def file_response_download(request, file_path): 59 | ext = os.path.basename(file_path).split('.')[-1].lower() 60 | # cannot be used to download py, db and sqlite3 files. 61 | if ext not in ['py', 'db', 'sqlite3']: 62 | response = FileResponse(open(file_path, 'rb')) 63 | response['content_type'] = "application/octet-stream" 64 | response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) 65 | return response 66 | else: 67 | raise Http404 68 | 69 | -------------------------------------------------------------------------------- /file_project/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyunbo/django-file-upload-download/a2657faa263ae1d7168cbed8bce556597dc8a369/file_project/__init__.py -------------------------------------------------------------------------------- /file_project/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyunbo/django-file-upload-download/a2657faa263ae1d7168cbed8bce556597dc8a369/file_project/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /file_project/__pycache__/settings.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyunbo/django-file-upload-download/a2657faa263ae1d7168cbed8bce556597dc8a369/file_project/__pycache__/settings.cpython-36.pyc -------------------------------------------------------------------------------- /file_project/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for file_project project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '1ai#)@_az=1a-zwtlq4e4#m#@*^84w#qp&!r+7&822ns_6^70d' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'file_upload', 41 | 'file_download', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'file_project.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'file_project.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ] 124 | 125 | # specify media root for user uploaded files, 126 | MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 127 | MEDIA_URL = '/media/' 128 | -------------------------------------------------------------------------------- /file_project/urls.py: -------------------------------------------------------------------------------- 1 | """file_project URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | from django.conf import settings 19 | from django.conf.urls.static import static 20 | 21 | urlpatterns = [ 22 | path('admin/', admin.site.urls), 23 | path('file/', include("file_upload.urls")), 24 | path('file/', include("file_download.urls")), 25 | ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 26 | -------------------------------------------------------------------------------- /file_project/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for file_project project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'file_project.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /file_upload/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyunbo/django-file-upload-download/a2657faa263ae1d7168cbed8bce556597dc8a369/file_upload/__init__.py -------------------------------------------------------------------------------- /file_upload/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /file_upload/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class FileUploadConfig(AppConfig): 5 | name = 'file_upload' 6 | -------------------------------------------------------------------------------- /file_upload/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from .models import File 3 | 4 | 5 | # Regular form 6 | class FileUploadForm(forms.Form): 7 | file = forms.FileField(widget=forms.ClearableFileInput(attrs={'class': 'form-control'})) 8 | upload_method = forms.CharField(label="Upload Method", max_length=20, 9 | widget=forms.TextInput(attrs={'class': 'form-control'})) 10 | 11 | def clean_file(self): 12 | file = self.cleaned_data['file'] 13 | ext = file.name.split('.')[-1].lower() 14 | if ext not in ["jpg", "pdf", "xlsx"]: 15 | raise forms.ValidationError("Only jpg, pdf and xlsx files are allowed.") 16 | # return cleaned data is very important. 17 | return file 18 | 19 | 20 | # Model form 21 | class FileUploadModelForm(forms.ModelForm): 22 | class Meta: 23 | model = File 24 | fields = ('file', 'upload_method',) 25 | 26 | widgets = { 27 | 'upload_method': forms.TextInput(attrs={'class': 'form-control'}), 28 | 'file': forms.ClearableFileInput(attrs={'class': 'form-control'}), 29 | } 30 | 31 | def clean_file(self): 32 | file = self.cleaned_data['file'] 33 | ext = file.name.split('.')[-1].lower() 34 | if ext not in ["jpg", "pdf", "xlsx"]: 35 | raise forms.ValidationError("Only jpg, pdf and xlsx files are allowed.") 36 | # return cleaned data is very important. 37 | return file 38 | 39 | -------------------------------------------------------------------------------- /file_upload/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyunbo/django-file-upload-download/a2657faa263ae1d7168cbed8bce556597dc8a369/file_upload/migrations/__init__.py -------------------------------------------------------------------------------- /file_upload/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | import os 3 | import uuid 4 | 5 | # Create your models here. 6 | # Define user directory path 7 | 8 | 9 | def user_directory_path(instance, filename): 10 | ext = filename.split('.')[-1] 11 | filename = '{}.{}'.format(uuid.uuid4().hex[:10], ext) 12 | return os.path.join("files", filename) 13 | 14 | 15 | class File(models.Model): 16 | file = models.FileField(upload_to=user_directory_path, null=True) 17 | upload_method = models.CharField(max_length=20, verbose_name="Upload Method") -------------------------------------------------------------------------------- /file_upload/templates/file_upload/ajax_upload_form.html: -------------------------------------------------------------------------------- 1 | {% extends "file_upload/base.html" %} 2 | {% block content %} 3 | 4 | {% if heading %} 5 |

{{ heading }}

6 | {% endif %} 7 | 8 |
9 | 10 | {% csrf_token %} 11 | {{ form.as_p }} 12 | 13 |
14 | 15 |
16 | {% endblock %} 17 | 18 | 19 | {% block js %} 20 | 21 | 82 | {% endblock %} -------------------------------------------------------------------------------- /file_upload/templates/file_upload/base.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | {% block title %}Django File Upload and Download{% endblock %} 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 | 16 | {% block content %} {% endblock %} 17 | 18 |
19 |
20 | 21 | 22 | 24 | 25 | 26 | 27 | 28 | {% block js %} {% endblock %} 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /file_upload/templates/file_upload/file_list.html: -------------------------------------------------------------------------------- 1 | {% extends "file_upload/base.html" %} 2 | 3 | {% block content %} 4 |

File List

5 |

RegularFormUpload | ModelFormUpload 6 | | AjaxUpload

7 | {% if files %} 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | {% for file in files %} 17 | 18 | 19 | 20 | 21 | 22 | 23 | {% endfor %} 24 | 25 |
Filename & URLFilesizeUpload Method
{{ file.file.url }}{{ file.file.size | filesizeformat }}{{ file.upload_method }}
26 | 27 | {% else %} 28 |

No files uploaded yet. Please click here 29 | to upload files.

30 | {% endif %} 31 | 32 | {% endblock %} -------------------------------------------------------------------------------- /file_upload/templates/file_upload/upload_form.html: -------------------------------------------------------------------------------- 1 | {% extends "file_upload/base.html" %} 2 | {% block content %} 3 | {% if heading %} 4 |

{{ heading }}

5 | {% endif %} 6 | 7 |
8 | {% csrf_token %} 9 | {{ form.as_p }} 10 | 11 |
12 | 13 | {% endblock %} -------------------------------------------------------------------------------- /file_upload/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /file_upload/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import re_path, path 2 | from . import views 3 | 4 | # namespace 5 | app_name = "file_upload" 6 | 7 | urlpatterns = [ 8 | 9 | # Upload File Without Using Model Form 10 | re_path(r'^upload1/$', views.file_upload, name='file_upload'), 11 | 12 | # Upload Files Using Model Form 13 | re_path(r'^upload2/$', views.model_form_upload, name='model_form_upload'), 14 | 15 | # Upload Files Using Ajax Form 16 | re_path(r'^upload3/$', views.ajax_form_upload, name='ajax_form_upload'), 17 | 18 | # Handling Ajax requests 19 | re_path(r'^ajax_upload/$', views.ajax_upload, name='ajax_upload'), 20 | 21 | # View File List 22 | path('', views.file_list, name='file_list'), 23 | 24 | ] -------------------------------------------------------------------------------- /file_upload/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | from .models import File 3 | from .forms import FileUploadForm, FileUploadModelForm 4 | import os 5 | import uuid 6 | from django.http import JsonResponse 7 | from django.template.defaultfilters import filesizeformat 8 | 9 | # Create your views here. 10 | 11 | 12 | # Show file list 13 | def file_list(request): 14 | files = File.objects.all().order_by("-id") 15 | return render(request, 'file_upload/file_list.html', {'files': files}) 16 | 17 | 18 | # Regular file upload without using ModelForm 19 | def file_upload(request): 20 | if request.method == "POST": 21 | form = FileUploadForm(request.POST, request.FILES) 22 | if form.is_valid(): 23 | # get cleaned data 24 | upload_method = form.cleaned_data.get("upload_method") 25 | raw_file = form.cleaned_data.get("file") 26 | new_file = File() 27 | new_file.file = handle_uploaded_file(raw_file) 28 | new_file.upload_method = upload_method 29 | new_file.save() 30 | return redirect("/file/") 31 | else: 32 | form = FileUploadForm() 33 | 34 | return render(request, 'file_upload/upload_form.html', {'form': form, 35 | 'heading': 'Upload files with Regular Form'}) 36 | 37 | 38 | def handle_uploaded_file(file): 39 | ext = file.name.split('.')[-1] 40 | file_name = '{}.{}'.format(uuid.uuid4().hex[:10], ext) 41 | # file path relative to 'media' folder 42 | file_path = os.path.join('files', file_name) 43 | absolute_file_path = os.path.join('media', 'files', file_name) 44 | 45 | directory = os.path.dirname(absolute_file_path) 46 | if not os.path.exists(directory): 47 | os.makedirs(directory) 48 | 49 | with open(absolute_file_path, 'wb+') as destination: 50 | for chunk in file.chunks(): 51 | destination.write(chunk) 52 | 53 | return file_path 54 | 55 | 56 | # Upload File with ModelForm 57 | def model_form_upload(request): 58 | if request.method == "POST": 59 | form = FileUploadModelForm(request.POST, request.FILES) 60 | if form.is_valid(): 61 | form.save() 62 | return redirect("/file/") 63 | else: 64 | form = FileUploadModelForm() 65 | 66 | return render(request, 'file_upload/upload_form.html', {'form': form, 67 | 'heading': 'Upload files with ModelForm'}) 68 | 69 | 70 | # Upload File with ModelForm 71 | def ajax_form_upload(request): 72 | form = FileUploadModelForm() 73 | return render(request, 'file_upload/ajax_upload_form.html', {'form': form, 74 | 'heading': 'File Upload with AJAX'}) 75 | 76 | 77 | # handling AJAX requests 78 | def ajax_upload(request): 79 | if request.method == "POST": 80 | # 1. Regular save method 81 | # upload_method = request.POST.get("upload_method") 82 | # raw_file = request.FILES.get("file") 83 | # new_file = File() 84 | # new_file.file = handle_uploaded_file(raw_file) 85 | # new_file.upload_method = upload_method 86 | # new_file.save() 87 | 88 | # 2. Use ModelForm als ok. 89 | form = FileUploadModelForm(data=request.POST, files=request.FILES) 90 | if form.is_valid(): 91 | form.save() 92 | # Obtain the latest file list 93 | files = File.objects.all().order_by('-id') 94 | data = [] 95 | for file in files: 96 | data.append({ 97 | "url": file.file.url, 98 | "size": filesizeformat(file.file.size), 99 | "upload_method": file.upload_method, 100 | }) 101 | return JsonResponse(data, safe=False) 102 | else: 103 | data = {'error_msg': "Only jpg, pdf and xlsx files are allowed."} 104 | return JsonResponse(data) 105 | return JsonResponse({'error_msg': 'only POST method accpeted.'}) 106 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'file_project.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | --------------------------------------------------------------------------------