Uploading an image from iPhone to .net ashx handler

五迷三道 提交于 2019-12-11 06:23:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10213634/uploading-an-image-from-iphone-to-net-ashx-handler

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