使用AFMultipartFormData AFNetworking 3.0上传图像

时间:2017-01-26 11:53:28

标签: objective-c afnetworking-3

NSURL *URL = [NSURL URLWithString:@"some APi"];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

UIImage *myImageObj = [UIImage imageNamed:@"avatar.jpg"];
NSData *imageData= UIImagePNGRepresentation(myImageObj);

[manager POST:URL.absoluteString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData
                                name:@"file"
                            fileName:@"avatar.jpg" mimeType:@"image/jpeg"];

    // etc.
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error: %@", error);
}];

我正在尝试使用afnetworking 3.0上传图片,但每次都会出现此错误

  

Domain = com.alamofire.error.serialization.response Code = -1011“请求   失败:内部服务器错误(500)“   UserInfo = {com.alamofire.serialization.response.error.response = {URL:some URL} {status   代码:500,headers {       “Access-Control-Allow-Origin”=“*”;       “内容长度”= 291;       “Content-Type”=“text / html”;       日期=“星期四,2017年1月26日11:41:19 GMT”;       Server =“Werkzeug / 0.11.11 Python / 2.7.12”; },

1 个答案:

答案 0 :(得分:3)

幸运的是,邮递员提供了Objective-C和其他一些语言代码,但AFNetworking我使用了这个

    NSURL *URL = [NSURL URLWithString:@"your URL"];

    UIImage *myImageObj = [UIImage imageNamed:@"image.jpg"];
    NSData *imageData= UIImageJPEGRepresentation(myImageObj, 0.6);

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //manager.responseSerializer=[AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];

    [manager POST:URL.absoluteString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData
                                    name:@"file"
                                fileName:@"image.jpg" mimeType:@"image/jpeg"];

        // etc.
    } progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"Response: %@", responseObject);

        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",string);

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