iOS 表单格式请求 formdata
2019-10-28 本文已影响0人
Tomboy_Anan
-(void)updateImageHeadWithUserID:(NSString *)userID imageUrl:(UIImage *)imageUrl complete:(void (^)(id))completeBlock{
NSString *url = [NSString stringWithFormat:@"%@%@v1/system/updateImageHead",AFURL,userGateway];
self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
@"text/html",
@"image/jpeg",
@"image/png",
@"application/octet-stream",
@"text/json",
@"text/javascript,multipart/form-data",
nil];
NSMutableDictionary *body = [[NSMutableDictionary alloc]init];
body[@"userId"] = userID;
[self POST:url parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
NSData *data = [self zipNSDataWithImage:imageUrl];
[formData appendPartWithFileData:data name:@"imageUrl" fileName:fileName mimeType:@"image/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (responseObject != nil) {
NSString *success = responseObject[@"success"];
if (success.intValue == 1) {
// 保存沙盒
NSString *path_document = NSHomeDirectory();
NSString *imagePath = [path_document stringByAppendingString:@"/Documents/userHeadImage.png"];
[UIImagePNGRepresentation(imageUrl) writeToFile:imagePath atomically:YES];
if (completeBlock) {
completeBlock(responseObject);
}
}else{
NSString *msg = responseObject[@"msg"];
[OJBProgressHUD OJBShowSvpErrorTitle:msg andTime:kNormalDelayTime andColor:YES];
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
if(data != nil){
NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
// 处理异常
NSString *message = errorDict[@"message"];
NSArray *array = [message componentsSeparatedByString:@"Failed:"];
[OJBProgressHUD OJBShowSvpErrorTitle:array[1] andTime:kNormalDelayTime andColor:YES];
}else{
[OJBProgressHUD OJBShowSvpErrorTitle:@"服务繁忙" andTime:kNormalDelayTime andColor:YES];
}
}];
}