How to get the size of an uploaded file in Django?

To retrieve the size of an uploaded file in Django, you can follow these steps:

  1. In the view function, the first step is to retrieve the uploaded file object, which is usually done by accessing request.FILES.
  2. Use the size property of the file object to retrieve the size of the file, measured in bytes.

The sample code is shown below:

from django.shortcuts import render
from django.http import HttpResponse

def upload_file(request):
    if request.method == 'POST' and request.FILES['file']:
        uploaded_file = request.FILES['file']
        file_size = uploaded_file.size
        return HttpResponse(f'Uploaded file size: {file_size} bytes')
    return render(request, 'upload_file.html')

In the example above, we first obtain the file object uploaded in the POST request, then use the size attribute to get the file’s size, and send it back to the client.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds