1

我正在尝试将图像上传到使用 create_upload_url() 创建的 URL,使用默认的 BlobstoreUploadHandler 处理它,并使用图像的 get_serving_url() URL 将 JSON 消息返回给客户端。我的代码如下:

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        response = {}

        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]

        response['error'] = False
        response['message'] = "Image uploaded."
        response['image_url'] = images.get_serving_url(blob_info.key())

        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(response))

app = webapp2.WSGIApplication(
    [('/_ih/upload_handler/', UploadHandler),
    ], debug=True)

问题是客户端没有收到响应。AppEngine 日志显示请求的状态为 200。使用 flash 发出请求时,状态码为 200 且没有响应正文,但使用 HTML5 会输出“(已取消)”状态。我不知道发生了什么。从我在互联网上看到的所有代码片段中,这应该可以工作。请帮忙!谢谢你。

4

2 回答 2

2

要处理上传并返回 JSON 响应,您需要从 upload_handler 重定向到将返回 JSON 响应的处理程序。

这是一个例子:

class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler):

    def post(self):
        blob_info = self.get_uploads()[0]       
        self.redirect(self.uri_for("successfulUpload",blob_key = blob_info.key()))


class SuccessfulUpload(BaseHandler):

    def get(self, blob_Key):
        response['error'] = False
        response['message'] = "Image uploaded."
        response['image_url'] = images.get_serving_url(blobstore.BlobKey(blob_Key))
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(response))
于 2013-02-09T07:29:18.457 回答
2

事实证明,这是一个 HTML5 跨域资源共享问题。您可以通过在响应中添加正确的标头来解决此问题:

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        response = {}

        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]

        response['error'] = False
        response['message'] = "Image uploaded."
        response['image_url'] = images.get_serving_url(blob_info.key())


        self.response.headers.add_header("Access-Control-Allow-Methods", "POST") 
        self.response.headers.add_header("Access-Control-Allow-Origin", "*")

        self.response.headers['Content-Type'] = 'application/json'

        self.response.out.write(json.dumps(response))
于 2013-02-18T04:15:43.657 回答