2010-07-12 2 views
2

가능한 경우 BlobStore에 대한 호출을 건너 뛸 수 있도록 Base64에서 사용자 (이 경우 신뢰할 수있는 관리자)의 이미지 데이터를 인코딩하려고했습니다. 나는 그것을 인코딩하려고 할 때마다, 나는라는 오류받을 : (?) 나는 오류 (덜 중요한 부분을) 봤하고 유니 코드를 함께 할 수있는 뭔가가있을 수 있습니다 것으로 나타났습니다Base64에서 AppEngine의 이진 업로드 데이터 인코딩

Error uploading image: 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128) 

합니다.

def post(self,id): 
    logging.info("ImagestoreHandler#post %s", self.request.path) 
    fileupload = self.request.POST.get("file",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: 
     (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) 

    img = Image(name=name, data=img_enc_struct) 
    img.put() 
    logging.info("Saved image to key %s", img.key()) 
    return (str(img.name), img.key()) 

내 이미지 모델 :

from google.appengine.ext import db 

class Image(db.Model): 

    name = db.StringProperty(required=True) 
    data = db.TextProperty(required=True) 
    created = db.DateTimeProperty(auto_now_add=True) 
    owner = db.UserProperty(auto_current_user_add=True) 

어떤 도움을 주시면 더 좋구요 템플릿 부분은 핸들러는 다음 코드를 포함하는 동안, 단지 기본 업로드 양식입니다. _store_image에서 이미지 인코딩을 뺀이 코드는 gvdent here의 blooger 브랜치에서 가져옵니다. 데이터 자체의 크기를 증가시키고 CPU의 인코딩과 디코딩 시간을 증가시킬 수있다 이진 데이터의 base64encode 하 점포 이미지 코드는 다음과 같이 될 수

+0

이미지 모델을 표시 할 수 있습니까? – iamgopal

+0

이미지 모델을 포함하도록 업데이트했습니다. – Matt

+0

오류는 유니 코드와 아무런 관련이 없습니다. 파이썬은 바이너리 데이터를 문자열로 인코딩하려고 시도하고 ASCII라고 가정하고 올바른 ASCII가 아니기 때문에 127보다 큰 바이트를 질식시킵니다. utf-8 데이터 (8 번째 비트를 사용하는 데이터)를 처리 할 때이 오류가 일반적으로 발생하지만 실제로는이 오류가 발생하지 않습니다. – geoffspear

답변

4

....

img = Image(name=name, data=file.read()) 
img.put() 
return (str(img.name), img.key()) 

.

및 Blobstore는 데이터 저장소와 동일한 저장소 구조를 사용하므로 파일 업로드 저장소 다운로드를 사용하기가 더 쉽습니다.