iOS AFNetWorking上传头像那点事

  • 创建网络管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

  • 设置响应数据类型
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", nil]]; 
  • 将要发送的文件进行上传
 [manager POST:url parameters:body constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 获取图片数据
        
        NSData *fileData = UIImageJPEGRepresentation(imageData, 1.0);
        // 设置上传图片的名字
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:fileData name:@"userfile" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 返回结果
         success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];

  • 参数
  • name : 上传文件的key
  • mimeType:image/png
  • fileName:上传图片时图片的名字根据

你可能感兴趣的:(iOS AFNetWorking上传头像那点事)