POST上传多张图片

/**
 * 上传带图片的内容,允许多张图片上传(URL)POST *
 *   @param url          网络请求地址
 *   @param images       要上传的图片数组
 *   @param parameter    图片数组对应的参数
 *   @param parameters   其他参数字典
 *   @param ratio        图片的压缩比例(0.0 ~ 1.0之间)
 *   @param succeedBlock 成功的回调
 *   @param failedBlock  失败的回调
 */
- (void)startMultiPartUploadTaskWithURL:(NSString *)url
                            imagesArray:(NSArray *)images
                            parameterOfimages:(NSString *)parameter
                            parametersDict:(NSDictionary *)parameters
                            compressionRatio:(float)ratio
                            succeedBlock:(void(^)(id operation, id responseObject))succeedBlock
                            failedBlock:(void(^)(id operation, NSError *error))failedBlock {
    
    if (images.count == 0) {
        NSLog(@"上传内容没有包含图片");
        return;
    }
    for (int i = 0; i< images.count; i++) {
        if (![images isKindOfClass:[UIImage class]]) {
            NSLog(@"images中第%d个元素不是UIImage对象",i+1);
            return;
            }
        }
    _manager = [AFHTTPSessionManager manager];
    [_manager POST:url parameters:parameters constructingBodyWithBlock:^(id _Nonnull formData) {
    int i = 0;
    //根据当前系统时间生成图片名称
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *dateStr = [formatter stringFromDate:date];
    for (UIImage *image in images) {
        NSString *fileName = [NSString stringWithFormat:@"%@%d.png", dateStr, i];
        NSData *imageData;
        if (ratio > 0.0f && ratio < 1.0f) {
                imageData = UIImageJPEGRepresentation(image, ratio);
            } else {
                imageData = UIImageJPEGRepresentation(image, 1.0f);
                }
              [formData appendPartWithFileData:imageData name:parameter fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) { //上传进度
    // NSLog(@"上传进度:%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id responseObject){
        succeedBlock(nil,responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failedBlock(nil,error);
    }];
}

你可能感兴趣的:(POST上传多张图片)