2017-02-25 91 views
0

我想將圖像上傳到服務器。服務器的服務是用.NET編寫的。現在服務器要求我發送圖像作爲數據字節不是multipart.I上傳文件由下面的代碼。我得到的響應文件上傳,但圖像不顯示。上傳文件到服務器沒有multipart在目標c?

[request setURL:[NSURL URLWithString:url]]; 
      [request setHTTPMethod:@"POST"]; 
      NSMutableData *body = [NSMutableData data]; 
      NSString *boundary = @"---------------------------14737809831466499882746641449"; 
      //NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 
      //[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

      [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
      [body appendData:[@"Content-Disposition: form-data; name=\"host_pic\"; filename=\"parkN.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
      [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
      [body appendData:postData]; 
      [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

      // close form 
      [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

     // setting the body of the post to the reqeust 
      [request setHTTPBody:body]; 

請解釋可能是什麼問題。我該如何上傳這樣的文件。

+0

檢查這個答案:http://stackoverflow.com/a/7289185/4831524 –

+0

那麼如何發送的字節數組server.Can請您更新mycode的? – iOSGuy

+0

爲檢查這個答http://stackoverflow.com/a/38263070/4831524 –

回答

0

然後你可以嘗試POST POST JSON格式。

NSError *error; 

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
NSURL *url = [NSURL URLWithString:@"<YOUR SERVER>"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 

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

[request setHTTPMethod:@"POST"]; 

UIImage *image = [UIImage imageNamed:@"image.png"]; 
NSString *byteArray = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; 

NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: byteArray, @"host_pic", 
        @"IOS TYPE", @"typemap", 
        nil]; 
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error]; 
[request setHTTPBody:postData]; 


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

}]; 

[postDataTask resume]; 
+0

API的人告訴我,我不必發送任何鍵作爲host_pic與上傳請求 – iOSGuy

+0

那麼你必須跟隨__multipart/form-data__上傳圖像 –

+0

API不支持多部分表單數據並且不能發送任何密鑰 – iOSGuy