Uploading Files in webapp2/GAE

余生长醉 提交于 2019-11-28 05:08:56

问题


I need to upload and process a CSV file from a form in a Google App Engine application based on Webapp2 (Python) I understand I could use blobstore to temporary store the file but I am curious to know if there is a way to process the file without having to store it at all.


回答1:


The content of uploaded files is in self.request.POST in your handler, so you can get that content (assuming e.g the field for the uploaded file is named 'foo') with e.g

content = self.request.POST.multi['foo'].file.read()

So now you have the content as a string -- process it as you wish. This does of course assume the thing will fit in memory (no multi-megabyte uploads!-)...




回答2:


If you need to upload a file via webapp2 with an HTML form, the first thing you need to do is change HTML form enctype attribute to multipart/form-data, so the code snippet seems like:

<form action="/emails" class="form-horizontal" enctype="multipart/form-data" method="post">
    <input multiple id="file" name="attachments" type="file">
</form>

In python code, you can read the file directly via request.POST, here's a sample code snippet:

class UploadHandler(BaseHandler):
    def post(self):
        attachments = self.request.POST.getall('attachments')

        _attachments = [{'content': f.file.read(),
                         'filename': f.filename} for f in attachments]


来源:https://stackoverflow.com/questions/27973109/uploading-files-in-webapp2-gae

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!