2013-04-03 16 views
5

私はDjangoとIOSの両方を新しくしました。私は、このmultipartデータの通過に立ち往生し、あなたの助言が必要です!IOSを搭載したDjango:POST経由でマルチパートデータ(json + image)を取得

現在、私は画像アップロード機能に取り組んでいます。クライアント側からは、画像ファイルを追加情報(例:access_token)とともに送信したいと考えています。サーバー側では、jsonデータをrequest.raw_post_dataおよびimage経由でreuqest.FILES経由で取得しようとしています。

私はJSONデータまたはImageのどちらかしか取得できませんでした。さらに悪い何、クライアント側にのみなし他の情報と500エラーを返す...

ここクライアントコードは

NSURL *url = [NSURL URLWithString:urlPath]; 
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 

// The parameter to send 
NSDictionary * params = dictionaryToSent; 

// the image need to upload 
NSData *imageData = UIImageJPEGRepresentation(image, 1); 
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { 
    [formData 
    appendPartWithFileData:imageData 
    name:@"image" 
    fileName:@"uniqueFileName" 
    mimeType:@"image/jpeg"]; 
}]; 

AFJSONRequestOperation* jsonOperation=[[AFJSONRequestOperation alloc]initWithRequest:request]; 

[jsonOperation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { 

    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite); 

}]; 

[jsonOperation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id JSON) { 

    // Handler for request is completed  
}failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    //Handler for request is failured; 
}]; 

[jsonOperation start]; 

だと私はサーバ側上の2つの方法を試してみました。 1は、第二の方法で、他のは、以下のようなものです私は500エラー

form = UploadFileForm(request.POST, request.FILES) 

を与えたフォーム(PLSインデントの問題を無視する)

data=json.loads(request.raw_post_data) 
ck_token = data['access_token'] 
if 'image' in request.FILES: 
upload = request.FILES['image'] 
filename = upload.name 
user = Basic.objects.get(ck_token = ck_token) 
post = Post(user_id = user.user_id, image = upload, caption = "Hello World") 
post.save() 
ret_json = { 
    'success': True, 
    'post_id': post.id 
} 
else: 
ret_json = { 
    'success': False, 
    'error_message': "image not found" 
} 

であり、私は画像がアップロードされますでしたが、何のaccess_tokenはは見つかりませんでした。私はaccess_tokenがどこに格納されているのだろうかと思っています。それとも、クライアント側の問題ですか?

あなたの助けが大変ありがとうございます。

+0

アクセストークンが基本的にすべてのリクエストでサーバーに送信されると仮定すると、単にヘッダーの認証トークンを維持しないのはなぜですか。私は何をしているのですか? – crizzwald

+0

@crizzwaldは提案に感謝します。それはおそらくより良い方法です:) – xialin

答えて

1

サーバー側の問題である必要があります。 request.raw_post_dataからの代わりに、トークン情報は実際にはrequest.POSTにあります。

ck_token = request.POST['access_token'] 
関連する問題