Reputation: 51
I'm new to Google app engine with python ,please help me!
Here is my html code:
<form action="" method="POST">
<div class="form-group">
<label for="uploaded_file">Attached file:</label>
<input type="file" id="uploaded_file" name="uploaded_file">
</div>
<div class="form-group">
<button class="btn-primary" type="submit">Save note</button>
</div>
</form>
Here is my python code:
def post(self):
uploaded_file = self.request.POST.get('uploaded_file')
file_name = getattr(uploaded_file, 'filename', None)
file_content = getattr(uploaded_file, 'file', None)
if uploaded_file:
self.response.out.write(uploaded_file)
self.response.out.write(file_name)
self.response.out.write(file_content)
I deploy my project to Google app engine and visit the website. I choose a picture and click the submit button, it can show uploaded_file(file's name). But, file_name and file_content show None.
If I modify my code :
def post(self):
uploaded_file = self.request.POST.get('uploaded_file')
file_name = getattr(uploaded_file, 'filename')
file_content = getattr(uploaded_file, 'file')
It will show:
File "C:\Users\pc2\Desktop\test\main.py", line 98, in post
file_name = getattr(uploaded_file, 'filename')
AttributeError: 'unicode' object has no attribute 'filename'
Someone help me to get file or picture ,please!
Upvotes: 0
Views: 97
Reputation: 55589
In your form, you need to an 'enctype' attribute so that uploaded files are handled properly - see this answer for more details on enctype. Your form tag should look like this:
<form action="" method="POST" enctype="multipart/form-data">
Change your post method to this:
def post(self):
uploaded_file = self.request.POST.get('uploaded_file')
file_name = getattr(uploaded_file, 'filename', None)
file_content = getattr(uploaded_file, 'file', None)
if uploaded_file is not None:
self.response.out.write(uploaded_file)
self.response.out.write(file_name)
self.response.out.write(file_content)
The change here is changing if uploaded_file:
to if uploaded_file is not None:
. This is because a successfully uploaded file will not be None, but would still fail your original if test. I would leave the 'None' arguments to getattr in place - these will prevent exceptions if the user clicks on submit but has not uploaded a file.
Finally, uploaded files do not have a file_content attribute, so this will always be None. If you want to access the file's raw bytes you will need to do
file_content = uploaded_file.file.read()
Note that the file content could be very large, and will not render as an image if you just write it out to the response - you'll just see the raw bytes.
Upvotes: 1