I'd like to read an uploaded file into a string. The file is not allowed if it is greater than 100k in size.
I've got the following code, but when I step through it using pdb, data is empty after the data = file.read() line executes.
def import_data(request):
params = {}
if request.method == 'POST':
pdb.set_trace()
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
data = file.read()
update_database(data)
else:
form = UploadFileForm()
params['form'] = form
return render_to_response('import_data.html',
params,
context_instance=RequestContext(request))
And this is my template:
% extends 'base.html' %}
{% block content %}
<form enctype="multipart/form-data" action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
Any ideas how to fix this?
When Django handles a file upload, the file data ends up placed in request. FILES (for more on the request object see the documentation for request and response objects). This document explains how files are stored on disk and in memory, and how to customize the default behavior.
Method 2: Find the path to the given file using os. In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.
class TemporaryUploadedFile [source] A file uploaded to a temporary location (i.e. stream-to-disk). This class is used by the TemporaryFileUploadHandler .
Have you looked into "Chunking" your uploads. What this basically does, is break your upload into multiple "chunks" as it saves it to the disk. I think this will help you upload larger files.
Regarding the empty file after "data = file.read()" executes, I think you can do something like file.seek(0) to bring the file pointer back to the beginning of the file. I'm guessing that the first read of the file is leaving the file pointer at the end of the file so it looks empty.
Hope this helps, Joe
The most common source of this issue is not adding the attribute enctype="multipart/form-data"
to the form tag in your HTML:
<form method="post" enctype="multipart/form-data">
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With