使用 Python Google App 引擎 API 将文件上传到 google 存储
upload file to google storage using Python Google App engine API
我正在关注 Massimiliano Pippi 的 Python Google App engine。在第 3 章中,我们试图上传一个文件,我的应用程序的用户 select 感谢这个 html 代码:
<div class="form-group">
<label for="uploaded_file">Attached file:</label>
<input type="file" id="uploaded_file" name="uploaded_file">
</div>
从 python 部分开始,在我的 MainHandler
on webapp2 中,我使用以下方法获取请求内容:
def post(self):
uploaded_file = self.request.POST.get("uploaded_file", None)
file_name = getattr(uploaded_file, 'filename')
file_content = getattr(uploaded_file, 'file', None)
content_t = mimetypes.guess_type(file_name)[0]
bucket_name = app_identity.get_default_gcs_bucket_name()
path = os.path.join('/', bucket_name, file_name)
with cloudstorage.open(path, 'w', content_type=content_t) as f:
f.write(file_content.read())
问题是变量 uploaded_file
被 Massimiliano Pippi 当作一个文件来处理,但是我的 Python 告诉我这个变量是一个包含文件名的 unicode。因此,当我尝试 file_name = getattr(uploaded_file, 'filename')
时,出现错误。
很明显书上的代码是假的,请问如何修改?
好的,在 Tim 的建议下,我查看了 WebOb 的文档并注意到在 html 文件中,我应该按如下方式放置 enctype="multipart/form-data"
:
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="uploaded_file">Attached file:</label>
<input type="file" id="uploaded_file" name="uploaded_file">
</div>
</form>
而不是:
<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>
</form>
我正在关注 Massimiliano Pippi 的 Python Google App engine。在第 3 章中,我们试图上传一个文件,我的应用程序的用户 select 感谢这个 html 代码:
<div class="form-group">
<label for="uploaded_file">Attached file:</label>
<input type="file" id="uploaded_file" name="uploaded_file">
</div>
从 python 部分开始,在我的 MainHandler
on webapp2 中,我使用以下方法获取请求内容:
def post(self):
uploaded_file = self.request.POST.get("uploaded_file", None)
file_name = getattr(uploaded_file, 'filename')
file_content = getattr(uploaded_file, 'file', None)
content_t = mimetypes.guess_type(file_name)[0]
bucket_name = app_identity.get_default_gcs_bucket_name()
path = os.path.join('/', bucket_name, file_name)
with cloudstorage.open(path, 'w', content_type=content_t) as f:
f.write(file_content.read())
问题是变量 uploaded_file
被 Massimiliano Pippi 当作一个文件来处理,但是我的 Python 告诉我这个变量是一个包含文件名的 unicode。因此,当我尝试 file_name = getattr(uploaded_file, 'filename')
时,出现错误。
很明显书上的代码是假的,请问如何修改?
好的,在 Tim 的建议下,我查看了 WebOb 的文档并注意到在 html 文件中,我应该按如下方式放置 enctype="multipart/form-data"
:
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="uploaded_file">Attached file:</label>
<input type="file" id="uploaded_file" name="uploaded_file">
</div>
</form>
而不是:
<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>
</form>