I have the HTML form which do prior upload of files via AJAX. So in django backend I have the following code of View, which process this AJAX calls:
@csrf_exempt
def book_upload(request):
if request.method == 'POST':
log.info('received POST to main book_upload view')
if request.FILES is None:
return HttpResponseBadRequest('Must have files attached!')
log.info('request has FILES')
file_types = (u'file_pdf', u'file_djvu', u'file_doc', u'file_epub', u'file_djvu', u'file_fb2', u'file_txt', u'file_chm', u'file_other');
file = None
file_type = None
for ft in file_types:
if ft in request.FILES:
file = request.FILES[ft]
file_type = ft
break
if file is None:
return HttpResponseBadRequest('Bad file type')
file_path = file.temporary_file_path()
result = {"path": file_path, "format": file_type}
response_data = simplejson.dumps(result)
if "application/json" in request.META['HTTP_ACCEPT_ENCODING']:
mimetype = 'application/json'
else:
mimetype = 'text/plain'
return HttpResponse(response_data, mimetype=mimetype)
else:
return HttpResponse('Only POST accepted')
But there is the problem in this code. It works on files more than 2.5 mb (because of TemporaryUploadedFile used than file size is > 2.5 mb by default settings). So and this code is based on idea that request.FILES contains object with TemporaryUploadedFile type. But in some cases I receive files with size < 2.5 mb. And request.FILES contains InMemoryUploadedFile.
So, I want do the following – each file, which is uploaded via ajax should be temporary stored. And memory is not a good place do that – because final re-storing files (after form submit) will not have information about this file in memory. So, the task is to “convert” InMemoryUploadedFile to TemporaryUploadedFile – is it possible?
PS
Maybe I should simply read file content from InMemoryUploadedFile object and write it to disk manually (to /tmp directory for example). How do you think?
PPS
And one another question – is it a good idea to do prior upload to temp directory?:) In my case the form have 6 input[type=file] elements, each of them upload different file type (six is for UI needs).
TIA!
You can override the default in
FILE_UPLOAD_HANDLERSin settings.py