ScottF
ScottF

Reputation: 571

Uploading an image from iPhone to .net ashx handler

I'm working on uploading an image from an iPhone to my server with an ashx script receiving the image. The problem I'm having is that regardless of everything I've tried context.Request.Files is empty.

Here is my xcode code

NSData *imageData = [[appDelegate currentProjectData] objectForKey:@"frontImage"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.****.com/iPhoneJpgUploadHandler.ashx"]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"- - - - - - - - - - Boundary String - - - - - - - - - -";
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--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"iphoneimage.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"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];
[request addValue:[NSString stringWithFormat:@"%d", [imageData length]] forHTTPHeaderField:@"Content-Length"];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);

And here is the code in my upload script

public void ProcessRequest (HttpContext context) {
    string uploadDir = "C:\\";

    if(context.Request.Files.Count > 0) {
        HttpPostedFile file = context.Request.Files[0];
        file.SaveAs(Path.Combine(uploadDir, file.FileName));
        context.Response.Write("success");
    } else {
        context.Response.Write("fail");
    }
}

The nslog in xcode writes out "fail" so it is running the script and returning. I'm not getting any errors. Any idea what I'm doing wrong?

Upvotes: 1

Views: 2050

Answers (1)

ScottF
ScottF

Reputation: 571

So I got it to work. All I changed is the boundary string from

NSString *boundary = @"- - - - - - - - - - Boundary String - - - - - - - - - -";

to this

NSString *boundary = @"xxxxBoundaryStringxxxx";

All I've read said it only had to be a string that didn't exist in the rest of the post data. I don't see how my first string could have but there may be other stipulations for it that I'm not aware of. Either way, it works now.

Upvotes: 1

Related Questions