使用AfNetworking上传图片

时间:2016-08-23 11:15:03

标签: ios objective-c afnetworking afnetworking-2 afnetworking-3

我正在尝试使用AFNetworking上传imageData(从gellery或相机中选择的图像并在UIImageview上设置)。这是我的代码:

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [[manager POST:setUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:image name:namePara fileName:@"abc.png"mimeType:@"image/png"];
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"Success: %@", responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }]resume];


我已经尝试了太多,但我意识到 uploadTaskWithStreamedRequest:request 块不再编译。而我的 responseObject 不再是日志了。
我该怎么做?

2 个答案:

答案 0 :(得分:0)

适用于AFNetworking 2.5版本:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager POST:@"Your_API" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
          [formData appendPartWithFileData:img_data name:@"param_name" fileName:@"abc.png"mimeType:@"image/png"];
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@", responseObject);


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

答案 1 :(得分:0)

你可以做点什么,

 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];


 [[manager POST:urlStrToUploadMedia parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

                    [formData appendPartWithFileData:dataToAppend name:mediaName fileName:mediaName mimeType:mimeType];

                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {

                    NSLog(@"response object : %@",responseObject);

                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

                    NSLog(@"failure : %@",error.localizedDescription);


                }]resume];

此处dataToAppendImage converted to NSDatamediaName为图片名称(无论您想提供什么),mimeType为mimeType,如image/jpeg或{{1对图像的类型进行处理。