Search code examples
.netobjective-ciosasp.net-mvcnsmutableurlrequest

What request headers to use for uploading an image file from iOS to ASP.NET?


I am building an iOS app where I want to upload images to an ASP.NET MVC server component like the posting of a file in a web page.

I have created the NSMutableURLRequest and NSConnection objects in iOS and have verified the call the the .NET server component is working.

NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
[request setTimeoutInterval:(interval==0?SERVICE_DEFAULT_TIMEOUT_INTERVAL:interval)];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SERVICE_BASEURL,url]]];
[request setHTTPMethod:@"POST"];
...

The image data is in an NSData object from an AVFoundation module

NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];

On the server the controller method in the .NET component is

[HttpPost]
public JsonResult UploadMedia(HttpPostedFileBase fileData)
{
 ...
  return Json(@"Success");
}

The goal is to transfer the image data to the server and store it. My questions are:

  1. What other HttpHeaderField values need to be created?
  2. How should I embed the image data in the NSMutableURLRequest?
  3. What type should be parameter be in the .NET component method?
  4. Based upon the type in #3 how should I extract the image data in the server component?

Solution

  • you can post data use multi-part form-data.

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                                            cachePolicy:NSURLRequestUseProtocolCachePolicy 
                                                       timeoutInterval:600];
    
    request.HTTPMethod = @"POST";
    
    NSString *boundry = @"---------------AF7DAFCDEFAB809";
    NSMutableData *data = [NSMutableData dataWithCapacity:300 * 1024];
    
    [data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n\r\n", @"field name"]
                                 dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:imgdata];   // data upload
    [data appendData:[[NSString stringWithString:@"\r\n"] 
                              dataUsingEncoding:NSUTF8StringEncoding]];
    
    [data appendData:[[NSString stringWithFormat:@"--%@\r--\n",boundry] 
                      dataUsingEncoding:NSUTF8StringEncoding]];
    
    request.HTTPBody = data;