上传图片 - Google App Engine + Python

时间:2013-09-10 17:23:40

标签: python html google-app-engine webapp2

我正在使用此链接作为上传图片的示例:

https://gist.github.com/jdstanhope/5079277

我的HTML代码:

 <form action="/upload_image" method="post" id="form1" runat="server">
       <div class="fileButtons">
         <input type='file' id="imgInp" name="imgInput" accept="image/*"/><br><br>
         <input type='button' id='remove' value='Remove' />
        </div></form>

main.py:

class SetImage(webapp2.RequestHandler):
    def post(self):
        logging.debug("test")
        id = str(self.request.get('id'))
        image = self.request.get('imgInput')

app = webapp2.WSGIApplication([('/upload_image', SetImage),
                               ('/', MainPage)], debug=True)

但是当我添加图像时,没有做任何事情,并且日志控制台无法打印:

logging.debug("test")

2 个答案:

答案 0 :(得分:1)

将图片上传到GAE的推荐方法是使用blobstore

以下是帮助您快速实现此目标的文档的快速细分:

进口:

import os
import urllib
import webapp2

from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

提供表格HTML。此表单使用选定的文件数据执行POST到GAE:

class MainHandler(webapp2.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        self.response.out.write('<html><body>')
        self.response.out.write('<form action="%s" method="POST"
                enctype="multipart/form-data">' % upload_url)
        self.response.out.write("""Upload File: 
                <input type="file" name="file"><br> <input type="submit"
                name="submit" value="Submit"> </form></body></html>""")

添加用于接收POST数据的处理程序(文件的二进制内容)。此函数的最后一行是将响应重定向到可以下载文件的位置:

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        # 'file' is file upload field in the form
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        self.redirect('/serve/%s' % blob_info.key())

使用上述UploadHandler添加处理程序以提供您上传的图像:

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info)

最后,定义应用的路线:

app = webapp2.WSGIApplication([('/', MainHandler),
                           ('/upload', UploadHandler),
                           ('/serve/([^/]+)?', ServeHandler)],
                            debug=True)

答案 1 :(得分:0)

关于日志语句未触发的问题:dev_appserver.py的默认日志级别为info,您可以使用--dev_appserver_log_level标记覆盖该日期级别。

参考new dev_appserver documentation

要从多部分/表单数据POST请求访问上传文件,request.POST中可以使用webapp2 documentation states