Stan described a good option with a buffer. Unfortunately, the disadvantage of this method is reading the file into memory. Another option is to use a temporarily saved file:
import tempfile import magic with tempfile.NamedTemporaryFile() as tmp: for chunk in form.cleaned_data['file'].chunks(): tmp.write(chunk) print(magic.from_file(tmp.name, mime=True))
Alternatively, you can check the file size:
if form.cleaned_data['file'].size < ...: print(magic.from_buffer(form.cleaned_data['file'].read())) else:
Optional :
The ability to use a name to open a file the second time the named temporary file is still open depends on the platform (it can be used on Unix; this is not possible on Windows NT or later).
So you might want to deal with this like this:
import os tmp = tempfile.NamedTemporaryFile(delete=False) try: for chunk in form.cleaned_data['file'].chunks(): tmp.write(chunk) print(magic.from_file(tmp.name, mime=True)) finally: os.unlink(tmp.name) tmp.close()
Alternatively, you might want to seek(0) after read() :
if hasattr(f, 'seek') and callable(f.seek): f.seek(0)
Where are the downloaded data stored?
source share