如何使用HTTPPost在服务器上上传图像/视频

时间:2013-09-18 10:05:04

标签: iphone ios objective-c file-upload

我正在尝试在我的服务器上传图片,但它总是返回“文件对象是NUll ”表示它没有收到我要发送的图片

我必须针对输入键“文件”上传图片 以及2个文本参数“ textParam1 ”和“ textParam2

我没有得到我错的地方,这是我的代码:

    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"Default.png"], 90);

// setting up the URL to post to
NSString *urlString = @"http://172.16.16.209:8080/xyz/upload.htm";
NSString *textParam1 = @"10";
NSString *textParam2 = @"ABCDEFGHIGH";

// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[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];

// file
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: attachment; name=\"testImage\"; filename=\"Default.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// text parameter 1
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"textParam1\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[textParam1 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// text parameter 2
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"textParam2\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[textParam2 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// set request body
[request setHTTPBody:body];

// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"returnString: %@",returnString);

针对要上传的图片传递参数“ file ”的位置。

url在本地eclipse上运行,无法在外部访问,但在android的情况下服务正常。

1 个答案:

答案 0 :(得分:0)

  

您应该看一下ASI框架   http://allseeing-i.com/ASIHTTPRequest/