Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/194.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在python中将上载的图像转换为字符串_Android_Python_Json_Image_Google App Engine - Fatal编程技术网

Android 在python中将上载的图像转换为字符串

Android 在python中将上载的图像转换为字符串,android,python,json,image,google-app-engine,Android,Python,Json,Image,Google App Engine,因此,我正在使用谷歌应用程序引擎(GoogleAppEngine)开发一个应用程序,我需要将一张图片从GAE传递到android客户端。为了做到这一点,我想用strig转换图片并将其作为json发送…(我发现这是一个很好的想法:) 问题是我很难在Base64中进行转换。我尝试过这种方法(),但它不适合我,因为我遇到了一个错误: File "/base/data/home/apps/s~testehan/1.366670408737847123/main.py", line 462, in po

因此,我正在使用谷歌应用程序引擎(GoogleAppEngine)开发一个应用程序,我需要将一张图片从GAE传递到android客户端。为了做到这一点,我想用strig转换图片并将其作为json发送…(我发现这是一个很好的想法:)

问题是我很难在Base64中进行转换。我尝试过这种方法(),但它不适合我,因为我遇到了一个错误:

 File "/base/data/home/apps/s~testehan/1.366670408737847123/main.py", line 462, in post
    img = Imagine( name=fileupload.filename, data=fileupload.file.read() )
  File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 970, in __init__
    prop.__set__(self, value)
  File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 614, in __set__
    value = self.validate(value)
  File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 2806, in validate
    value = super(UnindexedProperty, self).validate(value)
  File "/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 641, in validate
    raise BadValueError('Property %s is required' % self.name)
BadValueError: Property data is required
原因是,当我在日志中显示上传的_文件.file.read()时,我得到如下结果:

Content-Type: image/jpeg
Content-Length: 36187
X-AppEngine-Upload-Creation: 2013-04-14 08:35:46.123191
Content-MD5: MDYzNWE2Y2FkMzFlMGVhNzgwNmEwNzhiOGNkZTdhNTI=
Content-Disposition: form-data; name=img; filename="blabla.jpg"
所以我的问题是..我如何读取这个图像并将其存储为文本属性,以便能够传递它

谢谢

编辑:后处理程序

   class Imagine(db.Model):
    name = db.StringProperty(required=True)
    data = db.TextProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)

class PostImage(UserHandler):  
    def post(self, restaurant, category):
        logging.info("ImagestoreHandler#post %s", self.request.path)
        name= self.request.get('name')
        description= self.request.get('description')
        sizes = int(self.request.get('sizes'))

        fileupload = self.request.POST.get("img",None)
        if fileupload is None : return self.error(400)

        content_type = fileupload.type or getContentType( fileupload.filename )
        if content_type is None: 
            self.error(400)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write( "Unsupported image type: " + fileupload.filename )
            return
        logging.debug( "File upload: %s, mime type: %s", fileupload.filename, content_type )

        try:
            logging.info('citesc fisierul : ' + fileupload.file.read())
            img = Imagine( name=fileupload.filename, data=fileupload.file.read() )
            img.put()
            (img_name, img_url) = self._store_image( fileupload.filename, fileupload.file, content_type )
            self.response.headers['Location'] = img_url
            ex=None
        except Exception, err:
            logging.exception( "Error while storing image" )
            self.error(400)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write("Error uploading image: " + str(err))
            return
    #self.redirect(urlBase % img.key() )  #dummy redirect is acceptable for non-AJAX clients,
    # location header should be acceptable for true REST clients, however AJAX requests 
    # might not be able to access the location header so we'll write a 200 response with 
    # the new URL in the response body:

        acceptType = self.request.accept.best_match( listRenderers.keys() )
        out = self.response.out
        if acceptType == 'application/json':
            self.response.headers['Content-Type'] = 'application/json'
            out.write( '{"name":"%s","href":"%s"}' % ( img_name, img_url ) )
        elif re.search( 'html|xml', acceptType ):
            self.response.headers['Content-Type'] = 'text/html'
            out.write( '<a href="%s">%s</a>' % ( img_url, img_name) )

    def _store_image(self, name, file, content_type):
        """POST handler delegates to this method for actual image storage; as
        a result, alternate implementation may easily override the storage
        mechanism without rewriting the same content-type handling. 

        This method returns a tuple of file name and image URL."""

        img_enc = base64.b64encode(file.read())
        img_enc_struct = "data:%s;base64,%s" % (content_type, img_enc)
        logging.info('file name is '+name)
        logging.info('file is '+file.read())
        img = Imagine( name=name, data=file.read() )
        img.put()
        return ( str(img.name), img.key() )
类想象(db.Model):
name=db.StringProperty(必需=True)
data=db.TextProperty(必需=True)
created=db.DateTimeProperty(auto\u now\u add=True)
类PostImage(UserHandler):
def职位(自助、餐厅、类别):
logging.info(“ImagestoreHandler#post%s”,self.request.path)
name=self.request.get('name')
description=self.request.get('description')
size=int(self.request.get('size'))
fileupload=self.request.POST.get(“img”,无)
如果fileupload为None:返回self.error(400)
content\u type=fileupload.type或getContentType(fileupload.filename)
如果内容类型为“无”:
自身错误(400)
self.response.headers['Content-Type']='text/plain'
self.response.out.write(“不支持的图像类型:”+fileupload.filename)
返回
logging.debug(“文件上载:%s,mime类型:%s”,fileupload.filename,content\u类型)
尝试:
logging.info('citesc fisierul:'+fileupload.file.read())
img=Imagine(name=fileupload.filename,data=fileupload.file.read())
img.put()
(img_名称,img_url)=自存储_图像(fileupload.filename,fileupload.file,content_类型)
self.response.headers['Location']=img\u url
ex=无
除例外情况外,错误:
logging.exception(“存储图像时出错”)
自身错误(400)
self.response.headers['Content-Type']='text/plain'
self.response.out.write(“上传图像时出错:+str(err))
返回
#self.redirect(urlBase%img.key())#非AJAX客户端可以接受虚拟重定向,
#位置头对于真正的REST客户端应该是可以接受的,但是AJAX请求
#可能无法访问位置标头,因此我们将使用
#响应正文中的新URL:
acceptType=self.request.accept.best_match(listrenders.keys())
out=self.response.out
如果acceptType==“应用程序/json”:
self.response.headers['Content-Type']='application/json'
out.write(“{”name:“%s”,“href:“%s”}%”(img\u name,img\u url))
elif检索('html | xml',acceptType):
self.response.headers['Content-Type']='text/html'
输出。写入(“”%(img\u url,img\u名称))
定义存储图像(自身、名称、文件、内容类型):
“”“POST处理程序委托此方法进行实际图像存储;如下所示
因此,替代实施可能很容易覆盖存储
无需重写相同内容类型处理的机制。
此方法返回文件名和图像URL的元组。”“”
img_enc=base64.b64编码(file.read())
img\u enc\u struct=“数据:%s;base64,%s”%(内容类型,img\u enc)
logging.info('文件名为'+name)
logging.info('文件为'+file.read())
img=Imagine(name=name,data=file.read())
img.put()
return(str(img.name),img.key())
表格:

<form action="{{ upload_url }}" method="POST" enctype="multipart/form-data">
    <input name="name" placeholder="Product name" type="text" /> 
        <input type="file" name="img"/>
             <br />
    <input type="submit" value="Submit product!" />
</form>



为什么不将图像存储为BlobProperty,然后提供一个处理程序,允许android客户端在传递处理程序/图像的URL后将图像作为图像请求?此外,为了帮助解决您的特定问题,您还应该包含一些代码。例如,您如何从请求中获得
fileupload
?并向我们展示如何将图像发布到处理程序。它通常会有一个multipart/form dataHi Tim的内容配置…来回答你的第一个问题:因为我需要发出30-40个请求才能获得每个图像…在android客户端中,我有一个listView,每个项目都有一个图像。所以我认为有一个单一的json请求肯定会更快。而且我可以缓存这个jsonAlso。我尝试过这样做…但我遇到了一个没有人能帮助我的问题。。。但是那一次我用了一个blobreeference…仍然没有做到正确