我正在尝试将图像上传到使用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将输出状态“(已取消)”。我不知道发生了什么事。从我在互联网上看到的所有代码片段,这应该工作。请帮忙!谢谢。
答案 0 :(得分: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))
答案 1 :(得分: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))