1

我想發送一個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]; 

服務器不會在所有得到任何鍵...

+0

的NSData *爲imageData = UIImageJPEGRepresentation(圖像,1.0);試試這個 – 2014-09-23 17:10:02

+0

你最好是ASIHTTPREQUEST或AFNETWORKING庫。 – 2014-09-23 17:38:00

回答

0

這不是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 
+0

謝謝@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

+0

是的,哎呀,忘了NSJSONSerialization方法只適用於NSString,NSNull,NSNumber,NSArray和NSDictionary對象。您可以使用NSKeyedArchiver轉換爲NSData。 – 2014-09-23 17:59:28

0

使用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); 
}];