【发布时间】:2014-09-13 20:00:17
【问题描述】:
我正在尝试通过 POST 请求向服务器发送 avaudiorecorder。但由于某种原因我无法解决它没有上传。 我首先获取要发送的文件的路径,然后创建一个包含所有所需标头的 Post 请求方法。服务器响应是没有文件上传,所以我想我的文件路径有问题,但我没有得到解决方案。 我需要发送一个带有授权内容的 POST 请求,具有多部分表单数据和边界的内容类型,以及一个作为“uri_file”和文件上传的文件。 { uri_file : 文件 } 我尝试发送它,但服务器响应 -- NotEnoughData = "You must provide a file";--
...........
-(NSData *)sendTrack{
NSMutableDictionary *dictrvo = [NSMutableDictionary dictionaryWithObjectsAndKeys: audioRecorder.url,@"uri_file", nil ];
NSUserDefaults *prefs= [NSUserDefaults standardUserDefaults];
// get the audio data from main bundle directly into NSData object
NSURL *filePath = [prefs objectForKey:@"Revo1"];
if (filePath == nil) {
NSLog(@"vacio1");
}
NSData *result =[NSKeyedArchiver archivedDataWithRootObject:dictrvo];
NSData *archivo = [[NSData alloc] initWithContentsOfFile:filePath];
if (result == nil) {
NSLog(@"vacio");
}
NSData *response= [self createTrackPostRequest:archivo];
NSDictionary *dictionaryResponse = [self getDataFromJson:response];
return nil;
}
//发布请求方法
-(NSData *)createTrackPostRequest:(NSData *)requestData{
NSString *strData = [[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
// Print out new string
NSLog(@"DATA: %@",strData);
//URL
NSURL *URL = kRevoTrack;
if(URL == nil)
NSLog(@"estoy vacio");
//REQUEST
NSString *username;
NSString *api_key;
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
username = [prefs objectForKey:@"userName"];
api_key = [prefs objectForKey:@"api_key"];
NSString * authorizationcontent = [@"ApiKey " stringByAppendingString:[username stringByAppendingString:[@":" stringByAppendingString:api_key]]];
[request setHTTPMethod:@"POST"];
[request setValue:authorizationcontent forHTTPHeaderField:@"Authorization"];
[request setValue:@"multipart/form-data ; boundary = ---------1239821390213hdjfhsakdasjl123ad" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"form-data; name =\"uri_file\"; file =\"MyAudioMemo.m4a\"\r\n" forHTTPHeaderField:@"Content-Disposition"];
dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue: [NSString stringWithFormat: @"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:requestData];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(error == nil){
// REQUEST SENT WITHOUT ERROR
return result;
}else{
//ERROR SENDING THE REQUEST
NSLog(@"ERROR");
}
return nil;
}
有人可以帮我吗?非常感谢!
【问题讨论】:
标签: ios post httprequest nsurlconnection avaudiorecorder