2013-12-09 2 views
3

저는 python/django/tastypie에 익숙하며 파일 업로드를 시도하고 있습니다. 내가 알아낼 수없는 아주 이상한 (나에게 그것은) 오류가 발생하고있다. 내가 헤더가 설정 한Django/Tastypie 이미지 업로드 - 멀티 파트에서 유효하지 않은 경계 : 없음?

{ 
    "error_message" : "Invalid boundary in multipart: None", 
    "traceback" : "Traceback (most recent call last):\n\n File \"/Users/crown/Documents/Sources/Virtualenvs/GOCApi/lib/python2.7/site-packages/tastypie/resources.py\", line 195, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/Users/crown/Documents/Sources/GOCApi/api/resources/member.py\", line 85, in post_profile_picture\n if('image' in request.FILES):\n\n File \"/Users/crown/Documents/Sources/Virtualenvs/GOCApi/lib/python2.7/site-packages/django/core/handlers/wsgi.py\", line 214, in _get_files\n self._load_post_and_files()\n\n File \"/Users/crown/Documents/Sources/Virtualenvs/GOCApi/lib/python2.7/site-packages/django/http/request.py\", line 217, in _load_post_and_files\n self._post, self._files = self.parse_file_upload(self.META, data)\n\n File \"/Users/crown/Documents/Sources/Virtualenvs/GOCApi/lib/python2.7/site-packages/django/http/request.py\", line 176, in parse_file_upload\n parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)\n\n File \"/Users/crown/Documents/Sources/Virtualenvs/GOCApi/lib/python2.7/site-packages/django/http/multipartparser.py\", line 69, in __init__\n raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary)\n\nMultiPartParserError: Invalid boundary in multipart: None\n" 
} 

"콘텐츠 유형 : 다중/폼 데이터"뿐만 아니라이 같은 내 나머지 클라이언트 (CocoaRest 클라이언트) 다음과 같은 오류와 함께, 그것은 폭탄을 통해 사진을 업로드하려고 할 때마다 파일 탭에 추가 된 파일 나는 (request.FILES에서 '이미지')의 경우 이전에 인쇄 (요청)을 수행 할 때

def post_profile_picture(self, request, *args, **kwargs): 
     if(request.method == 'POST'): 
      if(str(request.META['CONTENT_TYPE']) != "multipart/form-data"): 
       return self.create_response(request, HelperMethods.api_return_msg("Unsupported media type"), response_class=http.HttpBadRequest) 
      else: 
       if('image' in request.FILES): 

        #bunch of code removed 

        return self.create_response(request, {"profile_img" : profile_img_key_name, "thumb_img" : thumb_img_key_name}, response_class=http.HttpResponse) 
       else: 
        return self.create_response(request, HelperMethods.api_return_msg("No image found"), response_class=http.HttpBadRequest) 
     else: 
      return self.create_response(request, HelperMethods.api_return_msg("Method not allowed"), response_class=http.HttpMethodNotAllowed) 

, 내가 같은 오류가 발생하지 않습니다 여기에

내가 클라이언트에서 호출 오전 내 방법입니다 , 그것은 실제로 다른 사람에게 점프하고 "No image found"를 인쇄합니다. 이것은 같은 방식으로 날려 버리지 않을 것이라고 이상합니다.

더 많은 헤더를 추가해야하는지 잘 모르겠습니다. "경계"를 설정하십시오. (그것이 무엇인지는 확실하지 않습니다.) ... 어떤 도움이 많이 주어집니다. 나는 더 나은 도움을 얻기 위해 사물을 시험해보고 여기에 결과를 게시하고자합니다. 감사!

답변

4

새로운 ModelResource를 만든 다음 Content-Type을 multipart/form-data로 설정했습니다. 경계 = 프론티어

어제 영업이 어제이긴하지만 10 시간은 많은 인터넷 검색 및 시행 착오입니다 ... smdh. 또한 PIL 이미지를 변경하기 위해 사용 된 후 이미지를 저장하는 아마존 S3를 사용

from tastypie import http, fields 
from django.conf.urls import url 
from tastypie.resources import ModelResource 
from api.helper_methods import HelperMethods 
from django.conf import settings 
from boto.s3.connection import S3Connection 
from boto.s3.key import Key 
import cStringIO 
from PIL import Image, ImageOps 

class FileUploadResource(ModelResource): 
    img = fields.FileField(attribute="img", null=True, blank=True) 
    class Meta: 
     allowed_methods = 'post' 
     resource_name = 'file_upload' 
     include_resource_uri = False 

    def prepend_urls(self): 
     return [ 
      url(r"^(?P<resource_name>%s)/$" % self._meta.resource_name, self.wrap_view('get_profile_picture'), name="api_get_profile_picture"), 
      url(r"^(?P<resource_name>%s)/profile_picture/$" % self._meta.resource_name, self.wrap_view('post_profile_picture'), name="api_post_profile_picture"), 
      ] 

    def get_profile_picture(self, request, **kwargs): 
     return self.create_response(request, HelperMethods.api_return_msg("Bad requested"), response_class=http.HttpBadRequest) 

    def post_profile_picture(self, request, **kwargs): 
     if(request.method == 'POST'): 
      if "multipart/form-data" not in str(request.META['CONTENT_TYPE']): 
       return self.create_response(request, HelperMethods.api_return_msg("Unsupported media type"), response_class=http.HttpBadRequest) 
      else: 
       if('image' in request.FILES): 
        upload = request.FILES['image'] 
        main_img = Image.open(upload) 

        profile_img = main_img.resize((200,200), Image.ANTIALIAS) 
        profile_img_io = cStringIO.StringIO() 
        profile_img.save(profile_img_io, 'PNG', quality=85) 

        thumb_img = main_img.resize((80,80), Image.ANTIALIAS) 
        thumb_img_io = cStringIO.StringIO() 
        thumb_img.save(thumb_img_io, 'PNG', quality=85) 

        conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) 
        bucket = conn.get_bucket(settings.BUCKET_NAME) 

        profile_img_key_name = HelperMethods.generate_pic_key() + ".png" 
        profile_img_key = Key(bucket) 
        profile_img_key.key = profile_img_key_name 
        profile_img_key.set_contents_from_string(profile_img_io.getvalue()) 
        profile_img_key.make_public() 

        thumb_img_key_name = HelperMethods.generate_pic_key() + ".png" 
        thumb_img_key = Key(bucket) 
        thumb_img_key.key = thumb_img_key_name 
        thumb_img_key.set_contents_from_string(thumb_img_io.getvalue()) 
        thumb_img_key.make_public() 

        return self.create_response(request, {"profile_img" : profile_img_key_name, "thumb_img" : thumb_img_key_name}, response_class=http.HttpResponse) 
       else: 
        return self.create_response(request, HelperMethods.api_return_msg("No image found"), response_class=http.HttpBadRequest) 
     else: 
      return self.create_response(request, HelperMethods.api_return_msg("Method not allowed"), response_class=http.HttpMethodNotAllowed) 

: 여기

모델 자원이다.

관련 문제