2011-03-08 73 views
1

我想將圖像,視頻和音頻文件上傳到服務器。我已閱讀this thread的類似主題,但無法完全理解代碼的流程。如果你能向我推薦一些示例代碼或教程,那就太好了。我使用下面的代碼,而無需任何介質連接到服務器通過xcode的多部分HTTP請求

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
NSString *url =[[NSString alloc]initWithFormat:@"%@",[NetworkConstants getURL]]; 
NSURL *theURL =[NSURL URLWithString:url]; 
[url release]; 
NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0.0f]; 
[theRequest setHTTPMethod:@"POST"]; 

NSString *theBodyString = [NSString stringWithFormat:@"json1=%@&userID=%@",jsonObject,[GlobalConstants getUID]]; 

NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding]; 
[theRequest setHTTPBody:theBodyData]; 

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

if (conn) { 
    NSLog(@"Successful in sending sync"); 
} 
else { 
    NSLog(@"Failed Connection in sending sync"); 
} 
[conn release]; 

這將是對我來說真的很方便,如果事情可以做編輯的這部分代碼。

任何形式的幫助將不勝感激。

在此先感謝!

+0

如果您正確標記了您的問題,您將會得到更好(或更多)的答案。僅僅因爲你使用xcode編寫代碼並不意味着它與xcode相關。 –

+0

感謝您的意見....將保持一個說明...... :) – devsri

回答

6

雖然回答我自己的問題還爲時過早,但我想到了將其添加到此處的解決方案。

爲了上面的代碼,我們只需要作以下修改

 NSData *imageData = UIImageJPEGRepresentation(attachedImage.image, 90); 
     NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"]; 
     NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
     [theRequest addValue:contentType forHTTPHeaderField:@"Content-Type"]; 


     NSMutableData *theBodyData = [NSMutableData data]; 
     [theBodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [theBodyData appendData:[@"Content-Disposition: form-data; name= \"server_value_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
     [theBodyData appendData:[yourString dataUsingEncoding:NSUTF8StringEncoding]]; 
     //this appends the image data 
     [theBodyData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [theBodyData appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"image\"; filename=\"1.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [theBodyData appendData:[[NSString stringWithString:@"Content-Type: image/jpg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [theBodyData appendData:[NSData dataWithData:imageData]]; 
     [theBodyData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [theRequest setHTTPBody:theBodyData]; 

而其餘部分保持相同的問題。

發送多部分請求時需要記住的一點是,服務器需要的所有參數都需要在邊界內使用,並且每個參數都應發送到單獨的邊界中。

希望這可以幫助其他人。

:)

+0

所以這是一個圖像。但是你知道如何上傳視頻嗎? – Supertecnoboff

+0

我需要上傳2個音頻文件,1個圖像和一些字符串..我該怎麼做? – Mak13