从UIImagePickerController发送UIImage POST到服务器?
我想发送一个UIImage与UIImagePickerController服务器开机自检以及其他相关的值。但我会在试图到字典值@“图像”设置为UIImageJPEGRepresentation(图像,1.0)行:从UIImagePickerController发送UIImage POST到服务器?
-(void)sendImageToServer:(UIImage *)image
{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4;
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:nil delegateQueue:queue];
NSURL *uploadURL = [NSURL URLWithString:@"http://...."];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSData *postData = [[NSData alloc] init];
[postData setValue:UIImageJPEGRepresentation(image, 1.0) forKey:@"image"];
[postData setValue:@"1" forKey:@"categories[0]"];
[postData setValue:@"4" forKey:@"categories[1]"];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:postData
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
NSError *err;
NSDictionary *JSONDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
NSLog(@"HTTP 200 response: %@", JSONDict);
});
} else {
NSLog(@"HTTP %ld status!", (long)httpResponse.statusCode);
}
} else {
NSLog(@"HTTP post image error: %@", error);
}
}];
[uploadTask resume];
}
JSON序列并不在这里工作,因为图像是不是有效的JSON值。另一方面,如果我尝试:
...
NSMutableData *postData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:postData];
[archiver encodeObject:UIImageJPEGRepresentation(image, 1.0) forKey:@"image"];
[archiver encodeObject:@"1" forKey:@"categories[0]"];
[archiver encodeObject:@"4" forKey:@"categories[1]"];
[archiver finishEncoding];
//NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:NSJSONWritingPrettyPrinted error:&jsonError];
//Now you can post the json data
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:postData
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {...
存档的关键:值对似乎没有得到服务器。这必须是一个常规的iOS编码任务。
即使我只是尝试:
NSError *jsonError;
NSData *postData = [NSJSONSerialization dataWithJSONObject:@{@"image":@"123",@"categories[0]":@"1",@"categories[1]":@"4"} options:NSJSONWritingPrettyPrinted error:&jsonError];
服务器不会在所有得到任何键...
这不是NSData
的正确使用。它现在正在崩溃,因为NSData
没有密钥命名图像(..或其后的两个)。你需要做的是创建一个NSDictionary
,然后将其转换为NSData
。
做这样的事情,而不是:
NSDictionary *dictionary = [NSDictionary alloc]initWithObjectsAndKeys:image,@"image",@(1),@"categories[0]",@(4),@"categories[1]", nil];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary]; //Not currently using NSJSONSerialization since you want to post a Dictionary with an invalid NSJSONSerialization type in it.
//Now you can post the json data
谢谢@tdevoy。我已经尝试过类似的东西,但它在同一个地方抛出异常: \t \t \t \t \t [NSJSONSerialization datataWithJSONObject ....];我假设JPEG表示不是有效的JSON值: NSDictionary * dataDict = @ {@“image”:UIImageJPEGRepresentation(image,1.0),@“categories [0]”:@“1”,@“categories [1] “:@”4“}; NSError * jsonError = nil; NSData * postData = [NSJSONSerialization dataWithJSONObject:dataDict options:NSJSONWritingPrettyPrinted error:&jsonError]; – izk 2014-09-23 17:24:31
是的,哎呀,忘了NSJSONSerialization方法只适用于NSString,NSNull,NSNumber,NSArray和NSDictionary对象。您可以使用NSKeyedArchiver转换为NSData。 – 2014-09-23 17:59:28
给人以AFNetworking一个尝试,它有一个伟大的方式,使上传,您可以在这里找到样本:https://github.com/AFNetworking/AFNetworking#creating-an-upload-task
我个人建议大家使用它,因为我开始使用我没有任何麻烦来与我的应用程序与网络服务器进行通信。
使用AFNetworking和多部分表单文章。下面是一个粗略的例子(注意,我传递一个块这样您的实施可能会有所不同):
AFHTTPRequestOperation *operation = [self POST:FullURLString parameters:Params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:fileData name:fileName fileName:fileName mimeType:mimeType];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData *responseData = [operation responseData];
id retObj;
NSError *error = nil;
if (responseData) {
retObj = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
}
// Pass back the serialized object (either an NSArray of type NSDictionaries or an NSArray of type customClass)
block(retObj);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failed with error = [Error]: %@", error);
block(nil);
}];
的NSData *为imageData = UIImageJPEGRepresentation(图像,1.0);试试这个 – 2014-09-23 17:10:02
你最好是ASIHTTPREQUEST或AFNETWORKING库。 – 2014-09-23 17:38:00