Django "Unable to determine the file's size" error with tempfile.TemporaryFile

Viewed 3507

I'm having problems with the standard Django FileField and tempfile.TemporaryFile. Whenever I try to save a FileField with the TemporaryFile, I get the "Unable to determine the file's size" error.

For example, given a model named Model, a filefield named FileField, and a temporaryfile named TempFile:

Model.FileField.save('foobar', django.core.files.File(TempFile), save=True)

This will give me the aforementioned error. Any thoughts?

5 Answers

I know this is a bit old but I've managed to save a base64 file (without having the actual file saved on the disk) by using the ContentFile class provided by Django.

According to the docs:

The ContentFile class inherits from File, but unlike File it operates on string content (bytes also supported), rather than an actual file.

The snippet below receives a base64 string, extract it's data and file extension and save it to an ImageField using the ContentFile class

import uuid
from django.core.files.base import ContentFile


def convert_b64data(b64data, filename):
    file_format, imgstr = b64data.split(';base64,')
    ext = file_format.split('/')[-1]
    return {
        'obj': base64.b64decode(imgstr),
        'extension': ext,
    }


b64data = request.data['b64file']
filename = str(uuid.uuid4())
file_data = convert_b64data(b64data, filename)
file_path = 'media/{}/{}.{}'.format(
            user.code,
            filename,
            file_data['extension']
        )
user.banner.save(file_path, ContentFile(file_data['obj']))
Related