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

倾然丶 夕夏残阳落幕 提交于 2019-12-24 08:32:03

问题


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?

回答1:


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;


来源:https://stackoverflow.com/questions/10200880/what-request-headers-to-use-for-uploading-an-image-file-from-ios-to-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!