1

我想将图像、视频和音频文件上传到服务器。我已经阅读了关于类似主题的这个帖子,但无法完全理解代码的流程。如果您能建议我一些示例代码或教程开始,那就太好了。我正在使用以下代码在没有任何媒体的情况下连接到服务器

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

如果可以编辑这部分代码对我来说真的很方便。

任何形式的帮助将不胜感激。

提前致谢!!

4

1 回答 1

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

其余的与问题中的相同。

只需要记住,在发送多部分请求时,服务器所需的所有参数都需要在边界中进行,并且每个参数都应该在单独的边界中发送。

希望这对其他人也有帮助。

:)

于 2011-03-09T08:02:28.507 回答