gpt4 book ai didi

ios - 带有 IOS : getting multipart data (json + image) via POST 的 Django

转载 作者:可可西里 更新时间:2023-11-01 04:53:30 25 4
gpt4 key购买 nike

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

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

最佳答案

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

ck_token = request.POST['access_token'] 

关于ios - 带有 IOS : getting multipart data (json + image) via POST 的 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com