iOS大杂烩

iOS 用AFN上传一个文件(如语音)

2016-09-28  本文已影响1715人  MrSYLong
    //用AFN的AFHTTPSessionManager
    AFHTTPSessionManager *sharedManager = [[AFHTTPSessionManager alloc]init];
    sharedManager1.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    sharedManager1.requestSerializer.timeoutInterval =20;
    NSString *url = [NSString stringWithFormat:@"你的url"];
    [sharedManager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //把语音文件转成data
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *amrPath = [path stringByAppendingString:@"/amrRecord.amr"];
        NSData *data = [NSData dataWithContentsOfFile:amrPath];
        //上传数据:FileData-->data  name-->fileName(固定,和服务器一致)  fileName-->你的语音文件名  mimeType-->我的语音文件type是audio/amr 如果你是图片可能为image/jpeg
        [formData appendPartWithFileData:data name:@"fieldName" fileName:@"amrRecord.amr" mimeType:@"audio/amr"];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"success");
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
//    sharedManager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    [sharedManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//    [sharedManager.requestSerializer setValue:@"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
上一篇下一篇

猜你喜欢

热点阅读