2011-03-08 139 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