我想發送一個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 *爲imageData = UIImageJPEGRepresentation(圖像,1.0);試試這個 – 2014-09-23 17:10:02
你最好是ASIHTTPREQUEST或AFNETWORKING庫。 – 2014-09-23 17:38:00