使用参数上传zip文件

时间:2013-04-05 11:27:00

标签: iphone objective-c ios5 multipartform-data

我正在尝试使用NSURLConnection方法使用POST上传文件。而且我需要在帖子中发送一些参数,如用户名等。 我从早上开始尝试这个请帮助我们。

1 个答案:

答案 0 :(得分:1)

NSString *urlString = @"http://test.com/upload.aspx";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = [NSString stringWithString:@"0xLhTaLbOkNdArZ"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

//Reading the file
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.zip"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];

NSMutableData *body = [NSMutableData data];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"test.zip\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:myData];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body]; 

NSError *returnError = nil;
NSHTTPURLResponse *returnResponse = nil;

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnResponse error:&returnError];

试试这个