2013-04-05 100 views
1

我想用POST方法使用NSURLConnection上傳文件。也需要發送像郵件用戶名等幾個參數。 我想這從早上起請幫助我的傢伙。使用參數上傳zip文件

+1

得到幫助的最佳方式,就是代碼的麻煩部分添加的問題。 – 2013-04-05 11:43:21

+0

我已經嘗試了很多方法,但沒有任何工作,所以我正在尋找一些新鮮的答案 – 2013-04-05 11:49:37

+0

這可能會幫助你:http://stackoverflow.com/questions/11024279/how-can-i-upload-file-and-other -parameter-使用-NSURLConnection的 – 2013-04-05 11:56:35

回答

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

試試這個