我制作了一个iphone应用来上传音频文件。
我还在asp.net中提供了webervices来支持这个应用程序的其他功能,并将它发布在godaddy服务器上。
我想从我的iphone应用程序上传/保存该服务器上的音频文件。
我搜索了许多代码,但它们没有相关性和实用性。
那我怎么能这样做呢?
如何获取可以上传文件的serverpath?
请为iphone提供一些示例代码。
答案 0 :(得分:3)
这是我将文件(可以是任何文件,图像,视频,音频)发布到网络服务的方式
NSString *fileName = @"myAudio";
NSData *audioFile = [NSData dataWithContentsOfFile:@"myAudio.ext"]; //some audio
NSString *urlString = @"http://www.something.com/someservice";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSString *strPostLength = [NSString stringWithFormat:@"%d", [audioFile length]];
NSMutableURLRequest *uRequest = [[NSMutableURLRequest alloc] init];
[uRequest setURL:url];
[uRequest setHTTPMethod:@"POST"];
if (audioFile)
{
NSMutableData *body = [NSMutableData data];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[uRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
/*
now lets create the body of the post
*/
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[uRequest setValue:strPostLength forHTTPHeaderField:@"Content-Length"];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.ext\"\r\n",fileName] dataUsingEncoding:NSUTF8StringEncoding]];
// userfile - >服务器代码中给出的变量名...
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:audioFile]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[uRequest setHTTPBody:body];
}
NSURLConnection *uConn=[[NSURLConnection alloc] initWithRequest:uRequest delegate:self];
if (uConn)
{
NSLog(@"Failed to connect to url");
}
uRequest = nil;
我希望这能帮助您解决问题...