2017-01-24 60 views
0

因爲我將圖像轉換爲base64字符串,並上傳它塞雷爾語用NSURLSessionsDataTask的示例 -如何通過NSUrlSession IOS發送的base64字符串

NSString *encodedString = [[self encodeToBase64String:imgParcel]stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]; 

[self.package.arrParcelImages addObject:encodedString] 

並把它發送這樣的...

NSDictionary *postParameters = @{@"userID":@"1",@"images":self.package.arrParcelImages} 

NSData *postData = [NSJSONSerialization dataWithJSONObject:postParameters options:NSJSONWritingPrettyPrinted error:&error]; 

NSString *dataString = = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]; 

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; 

NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil]; 


NSURL *url = [NSURL URLWithString:urlString]; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request addValue:@"image/png" forHTTPHeaderField:@"Content-Type"]; 

NSString *strValue = [NSString stringWithFormat:@"%@",[USER_DEFAULTS objectForKey:UD_X_API_VALUE]]; 
    if (strValue != nil) { 
     [request addValue:strValue forHTTPHeaderField:[USER_DEFAULTS objectForKey:UD_X_API_KEY]]; 
    } 

[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:postData]; 

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *taskData, NSURLResponse *taskResponse, NSError *taskError) { 
    //NSLog(@"Start - Response:%@ %@\n", taskResponse, taskError); 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     if (taskError) { 
      NSLog(@" Error = %@",[taskError localizedDescription]); 
      completionBlock(nil,taskError,task); 
     } 
     else { 
      NSError* error; 
      NSDictionary* json = [NSJSONSerialization JSONObjectWithData:taskData options:kNilOptions error:&error]; 

      if (json) { 
       NSLog(@" JSON = %@",json); 
      } 
      else { 
       NSString* newStr = [[NSString alloc] initWithData:taskData encoding:NSUTF8StringEncoding]; 
       NSLog(@"Error: %@",newStr); 

      } 

      completionBlock(json,nil,task); 
     } 

    }); 
}]; 
[postDataTask resume]; 

但這不是上傳base64字符串到服務器我在做什麼錯請幫忙

+0

順便說一句,'NSData * postData = postData = [NSJSONSerialization ...];'是不對的。擺脫額外的'postData'。同樣,'NSString * postString = = ...'是不正確的。你有一個額外的'='在那裏... – Rob

+0

我在這裏輸入了這就是爲什麼它看起來像這樣,但在代碼中它是完美的 –

回答

0

如果你在JSON中包含base64圖像,你不應該百分號轉義+個字符。您只有在創建x-www-form-urlencoded請求時才這樣做。

所以,請不要用%2B替換+個字符。


您正在設置Content-Type標題兩次。您的請求是JSON,因此請刪除image/png標題。一些網絡服務將會輕鬆地承擔內容類型,但也許你的頭被不正確的Content-Type標題弄糊塗了。


如果仍然沒有工作,問題可能或者是你怎樣創建圖像的再現的base64或者請求的格式不正確。 (a)最終請求看起來像什麼是很難知道的;和(b)服務器正在尋找什麼。

+0

但它仍然沒有上傳... –

+0

您的內容類型標題不是對。請參閱上面的擴展答案 – Rob

相關問題