Django with IOS:通过POST获取多部分数据(json+;图像)
我对Django和IOS都是新手。我被困在这个多部分数据传递中,需要你的建议 目前,我正在开发一个图像上传功能。从客户端,我想发送图像文件以及其他信息(例如访问令牌)。在服务器端,我尝试通过request.raw_post_数据获取json数据,并通过reuqest.FILES获取图像 事实证明,我只能获取JSON数据或图像,而不能同时获取两者。更糟糕的是,客户端只返回500个错误,没有其他信息 以下是客户端代码Django with IOS:通过POST获取多部分数据(json+;图像),ios,django,post,file-upload,django-forms,Ios,Django,Post,File Upload,Django Forms,我对Django和IOS都是新手。我被困在这个多部分数据传递中,需要你的建议 目前,我正在开发一个图像上传功能。从客户端,我想发送图像文件以及其他信息(例如访问令牌)。在服务器端,我尝试通过request.raw_post_数据获取json数据,并通过reuqest.FILES获取图像 事实证明,我只能获取JSON数据或图像,而不能同时获取两者。更糟糕的是,客户端只返回500个错误,没有其他信息 以下是客户端代码 NSURL *url = [NSURL URLWithString:urlPath
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];
另一个如下(请忽略压痕问题)
使用第二种方法,我可以上传图像,但找不到访问令牌。我想知道访问令牌存储在哪里-。-| | | |还是客户端的问题
非常感谢你的帮助 这应该是服务器端的问题。令牌信息实际上位于
request.post
中,而不是从request.raw\u post\u数据中获取。因此,这就像:
ck_token = request.POST['access_token']
假设访问令牌基本上会在每次请求时发送到服务器,为什么不将访问令牌保留在头auth中呢?这就是我所做的…@crizzwald谢谢你的建议。这可能是更好的方法:)
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"
}
ck_token = request.POST['access_token']