Performance: File upload handling basics
This affects page load speed and interaction responsiveness by managing how files are received and processed on the server.
from django.core.files.storage import default_storage from django.core.files.base import ContentFile from asgiref.sync import sync_to_async from django.http import HttpResponse async def upload_file(request): if request.method == 'POST': file = request.FILES['file'] await sync_to_async(default_storage.save)(file.name, ContentFile(file.read())) return HttpResponse('File uploaded asynchronously')
def upload_file(request): if request.method == 'POST': file = request.FILES['file'] with open('/tmp/' + file.name, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) return HttpResponse('File uploaded')
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous file save in request | Minimal | 0 | 0 | [X] Bad |
| Asynchronous file save with async views | Minimal | 0 | 0 | [OK] Good |
request.FILES in Django when handling file uploads?request.FILESrequest.POST holds form data, but request.FILES specifically holds file data.forms.FileField() is used in forms to accept any file upload.models.FileField() is for models, not forms. forms.ImageField() is for images only.def upload_file(request):
if request.method == 'POST':
uploaded_file = request.FILES['file']
with open('uploaded.txt', 'wb+') as destination:
for chunk in uploaded_file.chunks():
destination.write(chunk)
return HttpResponse('Upload complete')chunks() methodchunks() method reads the uploaded file in small parts to avoid loading the entire file into memory.def upload(request):
if request.method == 'POST':
file = request.POST['file']
with open('file.txt', 'wb') as f:
f.write(file.read())
return HttpResponse('Done')request.POST['file'], but uploaded files are in request.FILES.request.POST will cause a KeyError or wrong data type error.size attribute gives the file size in bytes.Pass the test and this pattern moves unknown