AFNetworking 3.0 实现form表单数据提交(转)

1、 先看下表单页面的HTML代码

第一张图片:

第二张图片:

2、 看完form表单的内容接下来我们来写客户端的提交代码
从上面的表单可以看出需要提交的内容有:json字符串和两张照片

    //需要提交的数据
    NSData  *data_f = UIImageJPEGRepresentation(zImage, 0.8);
    NSData  *data_s = UIImageJPEGRepresentation(fImage, 0.8);
    NSDictionary  * dic = [NSMutableDictionary new];
    [dic setValue:@"value1" forKey:@"key1"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];

    //配置AF
    AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
    [manage.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    manage.requestSerializer = [AFHTTPRequestSerializer serializer];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];

    [manage POST:@"提交的URL" parameters:nil constructingBodyWithBlock:^(id  _Nonnull formData) {
        //当提交一张图片或一个文件的时候 name 可以随便设置,服务端直接能拿到,如果服务端需要根据name去取不同文件的时候,则appendPartWithFileData 方法中的 name 需要根据form的中的name一一对应  
        [formData appendPartWithFormData:jsonData name:@"UploadData"];
        [formData appendPartWithFileData: data_f name:@"photoF" fileName:@"a.jpg" mimeType:@"image/jpeg"];
        [formData appendPartWithFileData: data_s name:@"photoS" fileName:@"b.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];

你可能感兴趣的:(AFNetworking 3.0 实现form表单数据提交(转))