我想将图像,视频和音频文件上传到服务器。我已经阅读了类似主题的this thread,但无法完全理解代码的流程。如果你可以建议我一些示例代码或教程,那将是很棒的。我使用以下代码连接,没有任何媒体到服务器
[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 :(得分: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];
其余的与问题中的相同。
在发送多部分请求时,只需记住服务器所需的所有参数都需要在边界内使用,并且每个参数都应在各个边界内发送。
希望这也有助于其他人。
:)