5

我是 Django 和 IOS 的新手。我陷入了这种多部分数据传递中,需要您的建议!

目前,我正在研究图像上传功能。从客户端,我想将图像文件与附加信息(例如 access_token)一起发送。在服务器端,我尝试通过 request.raw_post_data 获取 json 数据,并通过 reuqest.FILES 获取图像

事实证明,我只能获取 JSON 数据或图像,不能同时获取两者。更糟糕的是,客户端只返回 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];

我在服务器端尝试了两种方法。一个是给我500错误的表格

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

另一个如下(请忽略缩进问题)

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 存储在哪里-.-||| 还是客户端的问题?

非常感谢您的帮助!!!!

4

1 回答 1

1

应该是服务器端的问题。而不是从 获取request.raw_post_data,令牌信息实际上是在request.POST. 所以它会像:

ck_token = request.POST['access_token'] 
于 2013-08-06T08:48:11.367 回答