iOS经验总结

IOS 图片上传

2022-03-08  本文已影响0人  看谷秀

一: 上传图片 Base64

- (void)upLoadImagesRequest:(NSArray *)imagesArray {
    // 空图提示
    if(imagesArray.count==0){
        ShowTextPromptDelayHide(@"请至少选择一张图片", 2.0, self.view);
        return;
    }
    // 图片数组转NSData
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:imagesArray
                                                   options:NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments
                                                     error:nil];
    // 图片数组data 转json串
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    // 发送请求
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"user_id"]    = [TTUser uid];
        dict[@"imgs"]       = jsonString; // 图片数组字符串参数
        dict[@"title"]      = self.textField.text ? self.textField.text:@"";
        dict[@"remark"]     = self.detailView.text;
        NSLog(@"%@",dict);
     __weak typeof(self) weakSelf = self;
     [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [PPNetworkHelper POST:TTPlantPost parameters:dict responseCache:^(id responseCache) {
        // 缓存操作
    } success:^(id responseObject) {
        // 成功响应
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
        if([[responseObject objectForKeyEmptyObject:@"errcode"] intValue] == 0){//请求成功
            ShowTextPromptDelayHide(@"发送成功", 2.0, strongSelf.view);
            [strongSelf.navigationController popViewControllerAnimated:NO];
        }else{
            ShowTextPromptDelayHide([NSString stringWithFormat:@"%@",[responseObject objectOrNilForKey:@"msg"]], 2.0, strongSelf.view);
        };
    } failure:^(NSError *error) {
        // 失败响应
        ShowTextPromptDelayHide(@"发送失败", 2.0, self.view);
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
    }];
}

二: 上传图片 FormData

+ (void)uploadImages:(XXHttpRequestModel * _Nonnull)requestModel
    customizedConfig:(XXHttpUploadConfig *_Nullable)customizedConfig
            progress:(XXHttpProgress)progress
              result:(XXHttpResultBlock)result {
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    // 配置 上传路径
    NSString *baseUrl = [self baseUrl:customizedConfig type:XXHttpRequstUpload];
    NSString *httpUrl = [self httpUrl:requestModel customizedConfig:customizedConfig type:XXHttpRequstUpload];
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:baseUrl] sessionConfiguration:configuration];
    
    // 配置 1 请求响应类型  2 参数类型 3 超时设置 4 是否支持https配置cer证书
    [XXHttpService adjustManager:manager requestModel:requestModel customizedConfig:customizedConfig type:XXHttpRequstUpload];
    
    void (^success)(NSURLSessionDataTask * _Nonnull, id _Nullable) = ^void(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        [_allSessionTask removeObject:task];
        //转成json字典
        NSDictionary *responseJSON;
        if ([manager.responseSerializer isKindOfClass:[AFJSONResponseSerializer class]]) {
            responseJSON = responseObject;
        } else {
            responseJSON = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        }
        
        
        XXHttpLog(@"\n请求成功====请求地址:%@\n====请求头:%@\n====请求参数:%@\n====返回数据:%@\n", httpUrl,manager.requestSerializer.HTTPRequestHeaders, requestModel.parameters ,responseJSON);
        
        //装成Model
        XXHttpResponse *response = [XXHttpResponse initWithResponse:responseJSON taskResponse:task.response];
        
        
        //after block
        if (customizedConfig) {
            if (customizedConfig.commonResultBlock) {
                customizedConfig.commonResultBlock(response, nil);
            }
        } else {
            if (_defaultUploadConfig.commonResultBlock) {
                _defaultUploadConfig.commonResultBlock(response,nil);
            }
        }
        
        if (result) {
            result(response, nil);
        }
        
    };
    
    void (^failure)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull) = ^void(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [_allSessionTask removeObject:task];
        XXHttpLog(@"\n请求失败====请求地址:%@\n====请求头:%@\n====请求参数:%@\n====返回数据:%@\n", httpUrl,manager.requestSerializer.HTTPRequestHeaders, [requestModel.parameters convertToJSONData]  ,error);
        
        XXHttpResponse *response = [XXHttpResponse initWithResponse:nil taskResponse:task.response error:error];
        
        //after block
        if (customizedConfig) {
            if (customizedConfig.commonResultBlock) {
                customizedConfig.commonResultBlock(response, error);
            }
        } else {
            if (_defaultUploadConfig.commonResultBlock) {
                _defaultUploadConfig.commonResultBlock(response,error);
            }
        }
        
        if (result) {
            result(response, error);
        }
        
    };
    //before block
    if (customizedConfig) {
        if (customizedConfig.beforeBlock) {
            customizedConfig.beforeBlock(requestModel.parameters);
        }
    } else {
        if (_defaultUploadConfig.beforeBlock) {
            _defaultUploadConfig.beforeBlock(requestModel.parameters);
        }
    }
    
    NSURLSessionTask *sessionTask = [manager POST:httpUrl parameters:requestModel.parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 遍历images(image数组)
        for (NSUInteger i = 0; i < requestModel.images.count; i++) {
            // 图片经过等比压缩后得到的二进制文件
            NSData *imageData = UIImageJPEGRepresentation(requestModel.images[i], requestModel.imageScale ?: 1.f); // requestModel.imageScale 默认1.0 区间(0.f ~ 1.f) 本次设置的是0.1
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.%@",str,i,requestModel.imageType];
            
            [formData appendPartWithFileData:imageData
                                        name:requestModel.uploadImageName // 默认 file
                                    fileName: imageFileName // 上传文件名称
                                    mimeType:[NSString stringWithFormat:@"image/%@",requestModel.imageType]];
                                    // imageType 默认jpg
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress) : nil;
        });
    } success:success failure:failure];
   // 开始上传
    sessionTask ? [_allSessionTask addObject:sessionTask] : nil ;
}
上一篇下一篇

猜你喜欢

热点阅读