问题
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:
- What other HttpHeaderField values need to be created?
- How should I embed the image data in the NSMutableURLRequest?
- What type should be parameter be in the .NET component method?
- 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