使用参数上传zip文件

问题描述:

我想用POST方法使用NSURLConnection上传文件。也需要发送像邮件用户名等几个参数。 我想这从早上起请帮助我的家伙。使用参数上传zip文件

+1

得到帮助的最佳方式,就是代码的麻烦部分添加的问题。 – 2013-04-05 11:43:21

+0

我已经尝试了很多方法,但没有任何工作,所以我正在寻找一些新鲜的答案 – 2013-04-05 11:49:37

+0

这可能会帮助你:http://*.com/questions/11024279/how-can-i-upload-file-and-other -parameter-使用-NSURLConnection的 – 2013-04-05 11:56:35

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

试试这个