基于AFNetworking的图片上传,单张,多张

+ (void)uploadImageWithUrl: (NSString *)url Parameters: (id)parameter UploadImage :(UIImage *)uploadImage Success: (void (^) (id responseObject))success Failure: (void (^) (NSError *error))failure {
    
    AFHTTPSessionManager *Manager = [self sharedHTTPSession];
    [Manager POST:url parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        if (uploadImage != nil) {
            NSData *imgData = UIImageJPEGRepresentation(uploadImage, 0.05);
            [formData appendPartWithFileData:imgData name:@"coverFile" fileName:@"png" mimeType:@"image/png"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}
#pragma mark 上传多张图片
+ (void)uploadImageWithPath:(NSString *)path photos:(NSArray *)photos params:(NSDictionary *)params currentProgress:(progressBlock)currentProgress success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure
{
   
    AFHTTPSessionManager *manager = [self sharedHTTPSession];
    [manager POST:path parameters:params constructingBodyWithBlock:^(id  _Nonnull formData) {
        for (int i = 0; i < photos.count; i ++) {
            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            formatter.dateFormat=@"yyyyMMddHHmmss";
            NSString *str=[formatter stringFromDate:[NSDate date]];
            NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
            UIImage *image = photos[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.28);
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"coverFile%d",i+1] fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        currentProgress(uploadProgress);
        NSLog(@"uploadProgress is %lld,总字节 is %lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success){ ;
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

你可能感兴趣的:(基于AFNetworking的图片上传,单张,多张)