2017-02-25 90 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