I am trying to send images and text from an iPhone application to a asp.net webpage.
By following this example I now have the following method in xcode for uploading an image:
- (BOOL) uploadData {
NSData *imageData = UIImageJPEGRepresentation([serviceForm image], 0.9);
NSString *urlString = @"http://someUrl/SubmitSchema.ashx";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
BOOL success = [returnString isEqualToString:@"ok"];
[returnString release];
return success;
}
At the bottom on the same article there is a suggestion about creating an asp.net generic handler. Based on this, I have the following simple code for saving the image:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
foreach (var name in context.Request.Files.AllKeys)
{
var file = context.Request.Files.Get(name);
SaveFile(file);
}
}
private void SaveFile(HttpPostedFile file)
{
var fileName = Path.GetFileName(file.FileName);
var path = "C:\\Test\\" + fileName;
file.SaveAs(path);
}
This works and the image is saved, but I have not yet managed to include a string of text in the same post. The text I want to send can be quite long, and I suppose it is better to include this in the posted data rather than as a query string?
How would you add some text to the posted data and read it in .net?