2011-03-30 119 views
3

我想將圖像數據發送到服務器,爲此,我已將該數據附加到請求的HTTP正文併發送給它。我正在使用下面的代碼。將圖像數據(NSData)發送到服務器

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setURL:[NSURL URLWithString:@"http://developers.our-works.com/forms/TestReceiver.aspx"]]; 
[request setHTTPMethod:@"POST"]; 

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

// now lets create the body of the post 
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=\"%@\"\r\n",tempFileName] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[NSData dataWithData:imgdata]]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

//data into the string..... verifying............ 
NSString *strTest = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",strTest); 

// setting the body of the post to the request 
[request setHTTPBody:body]; 

// now lets make the connection to the web 
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

現在我必須發送兩個不同圖像的NSData。所以,只是想問一下,我可以將這兩個不同的圖像的NSData發送到上面的同一個主體中。 或者,我必須爲其他圖像的數據編碼相同的東西。

請幫我解決這個問題。感謝您。

回答

2

一個小建議:這是比較容易使用Ben Copsey的ASIHTTPRequest將POST數據發送到服務器。

您不需要編寫兩次POST兩個不同的圖像,只需用不同的鍵兩次插入圖像。請參閱以下示例(使用ASIHTTPRequest)

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 
[request setPostValue:@"Ben" forKey:@"first_name"]; 
[request setPostValue:@"Copsey" forKey:@"last_name"]; 
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"]; 
[request setFile:@"/Users/ben/Desktop/ben2.jpg" forKey:@"photo2"]; 
[request startSynchronous];