将图像从iPhone上传到.net ashx处理程序

时间:2012-04-18 16:19:25

标签: .net ios xcode upload image-upload

我正在努力将图像从iPhone上传到我的服务器,并使用ashx脚本接收图像。我遇到的问题是,无论我做过什么,我都尝试过context.Request.Files是空的。

这是我的xcode代码

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);

以下是我上传脚本中的代码

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");
    }
}

xcode中的nslog写出“失败”,因此它正在运行脚本并返回。我没有收到任何错误。知道我做错了吗?

1 个答案:

答案 0 :(得分:1)

所以我得到了它的工作。我改变的只是来自

的边界字符串
NSString *boundary = @"- - - - - - - - - - Boundary String - - - - - - - - - -";

到这个

NSString *boundary = @"xxxxBoundaryStringxxxx";

我读过的所有内容都说它只是一个字符串,在其余的帖子数据中不存在。我不知道我的第一根弦怎么可能有,但可能还有其他规定,我不知道。无论哪种方式,它现在都有效。