1

我有一个要求,我在服务器上上传一个波形文件,服务器给我返回那个文件的 URL。

我用过这个代码..

- (void)callUploadWS
{
NSString *vidURL = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"wav"];
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:vidURL]];

NSURL *url = [NSURL URLWithString:@"http://6.6.237.190"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
//  NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"Romantic.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/recorder/convert.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:videoData name:@"file" fileName:@"speech.wav" mimeType:@"audio/vnd.wave"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
// [httpClient enqueueHTTPRequestOperation:operation];

[operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(@"Success : %@",responseObject);}
                                  failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                      NSLog(@"error: %@",  operation.responseString);

                                      NSLog(@"error: %@", error.userInfo);
                                  }];
[operation start];
}

它正在上传文件并给我这个回复......

Success : <7b226669 6c65223a 22687474 703a5c2f 5c2f352e 392e3233 372e3135 305c2f72 65636f72 6465725c 2f75706c 6f61645c 2f353237 32336564 32366531 63662e77 6176227d>

但它应该给出这样的回应..

{
file: "http://6.6.237.190/recorder/upload/52723ef52972d.wav"
}

为什么这会给出二进制响应?

4

2 回答 2

2

您必须像这样将 responseObject 转换为 NSString

NSString *responseString=[NSString stringWithUTF8String:[responseObject bytes]];
于 2013-10-31T11:44:55.573 回答
0

@Gagan Kumar 给出了非常好的答案,但它的代码只有一半。它会将您的 json 响应转换为字符串。
因此,您无法从中获取字典,也无法解析文件 URL。为此,您必须使用此代码将字符串重新序列化为 json。

NSString *responseString=[NSString stringWithUTF8String:[responseObject bytes]];

NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
if (e) {
      NSLog(@"error : %@",e);
}else{
      NSLog(@"JSON : %@",JSON);
}

这将返回可解析的 json 对象。
希望它有所帮助。

于 2013-11-01T13:40:41.847 回答