iOS-------AFNetworking图片上传

2017-05-24  本文已影响31人  lizhi_boy

具体代码如下

/**
 @param urlStr api(接口)
 @param data_parnemts 传递的参数(如果传递的是图片,key为文件名(后台定),value为NSData(image转data))
 @param callBack 返回状态信息
 */
+(void)requestUrl:(NSString *)urlStr parmeters:(NSDictionary *)data_parnemts callBack:(void (^)(id, NSError *))callBack{
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [data_parnemts enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[NSData class]]) {
               [formData appendPartWithFileData:obj name:key fileName:key mimeType:@"image/jpeg"];
            }else{
                [formData appendPartWithFormData:[obj dataUsingEncoding:kCFStringEncodingUTF8] name:key];
            }
        }];
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    //设置服务器返回内容的接受格式
    AFHTTPResponseSerializer *responseSer = [AFHTTPResponseSerializer serializer];
    responseSer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    manager.responseSerializer = responseSer;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            callBack(nil,error);
        } else {   
            NSDictionary *objf = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:NULL];
            callBack(objf,nil);
        }
    }];
    [uploadTask resume];
}

图片转NSData:

//image转data
 UIImage *image = [UIImage imageNamed:@"name"];
 NSData* imgData= UIImageJPEGRepresentation(image, 1.0);
上一篇下一篇

猜你喜欢

热点阅读