单张图片上传
// 1.请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
NSString *url = [NSString stringWithFormat:@"%@/App/Index/userphoto/",SERVERURL];
// 2.拼接请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"mobile"] = self.userMobileLbl.text;
// 3.发送请求
[mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 拼接文件数据
NSData *data = UIImageJPEGRepresentation(localImg, 1.0);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
[formData appendPartWithFileData:data name:@"img1" fileName:fileName mimeType:@"image/jpg"];
} success:^(AFHTTPRequestOperation *operation, NSDictionary *json) {
// LXLog(@"%@", json);
[MBProgressHUD hideHUD];
[json[@"status"] isEqual: @"1"] ? [MBProgressHUD showSuccess:@"上传成功!"]:[MBProgressHUD showError:@"上传失败!"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[MBProgressHUD showError:@"上传头像失败,请重新上传"];
}];
批量上传图片
获取一张图片:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//获取编辑款中的图片
//UIImage *pickedImage = [info valueForKey:UIImagePickerControllerEditedImage];
//获取整张图片
UIImage *pickedImage = [info valueForKey:UIImagePickerControllerOriginalImage];
CGSize imgSize = pickedImage.size ;
if (imgSize.width > imgSize.height)
imgSize.height = imgSize.width;
else
imgSize.width = imgSize.height;
NSData *data = UIImageJPEGRepresentation(pickedImage, 0.6);
NSString *fileName = [NSString stringWithFormat:@"%@.jpg",[GlobelConfig getNowTimeTimestamp]];
[self startUploadFile:data fileName:fileName isMultiple:NO imgAry:@[]];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
获取多张图片:
TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:100 delegate:self];
[imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray * assets, BOOL isSelectOriginalPhoto) {
NSMutableArray *files = [@[] mutableCopy];
NSMutableArray *imgAry = [@[] mutableCopy];
for (NSInteger i = 0; i<photo.count; i++) {
UIImage *img = photo[i];
NSString *fileName = [NSString stringWithFormat:@"%@-%ld.jpg",[GlobelConfig getNowTimeTimestamp],i];
NSData *data = UIImageJPEGRepresentation(img, 0.6);
NSDictionary *dic = @{@"data":data,@"fileName":fileName};
[imgAry addObject:img];
[files addObject:dic];
}
NSData *fileData = [NSKeyedArchiver archivedDataWithRootObject:imgAry];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg",[GlobelConfig getNowTimeTimestamp]];
[self startUploadFile:fileData fileName:fileName isMultiple:YES imgAry:imgAry];
}];
[self presentViewController:imagePickerVc animated:YES completion:nil];
开始上传:
- (void)startUploadFile:(NSData*)fileData fileName:(NSString *)fileName isMultiple:(BOOL)isMultiple imgAry:(NSArray *)imgAry
{
[SVProgressHUD show];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer.timeoutInterval = 60;
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
if (NToken != nil) {
[manager.requestSerializer setValue:NToken forHTTPHeaderField:@"x-access-token"];
}
NSString * urlStr;
if (isMultiple) {
/ /批量上传
urlStr = kFileUploadBatch(@"7");
}else{
urlStr = NFileUpload(@"7");
}
[manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData){
if (isMultiple) {
/ /批量上传
for (int i = 0; i < imgAry.count; i++) {
UIImage *image = imgAry[i];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSArray *nameAry = [fileName componentsSeparatedByString:@"."];
NSString *lastStr = nameAry[nameAry.count - 1];
NSString *fileNameStr = [NSString stringWithFormat:@"%@-%d.%@", str,i,lastStr];
//上传的参数(上传图片,以文件流的格式)
[formData appendPartWithFileData:imageData
name:@"files"
fileName:fileNameStr
mimeType:@"image/jpeg/pdf/doc"];
}
}else{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSArray *nameAry = [fileName componentsSeparatedByString:@"."];
NSString *lastStr = nameAry[nameAry.count - 1];
NSString *fileNameStr = [NSString stringWithFormat:@"%@.%@", str,lastStr];
//上传的参数(上传图片,以文件流的格式)
[formData appendPartWithFileData:fileData
name:@"file"
fileName:fileNameStr
mimeType:@"image/jpeg/pdf/doc"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
//打印下上传进度
//NSLog(@"上传进度");
//NSLog(@"%@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[SVProgressHUD dismiss];
//上传成功
//NSLog(@"%@",responseObject);
NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
if ([resultDictionary[@"code"] integerValue] == 1){
if (isMultiple) {
// 多图
NSArray *data = resultDictionary[@"data"];
for (NSDictionary *dataDic in data) {
NSDictionary *dic = @{@"fileName":fileName,@"fileKey":[GlobelConfig getNullStr:dataDic[@"key"]],@"fileSize":[GlobelConfig getNullStr:dataDic[@"fileSize"]]};
[self.carFileAry addObject:dic];
}
}else{
NSDictionary *data = resultDictionary[@"data"];
NSDictionary *dic = @{@"fileName":fileName,@"fileKey":[GlobelConfig getNullStr:data[@"key"]],@"fileSize":[GlobelConfig getNullStr:data[@"fileSize"]]};
[self.carFileAry addObject:dic];
}
[self.mainTableView reloadData];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[SVProgressHUD dismiss];
//上传失败
NSLog(@"上传失败");
[SVProgressHUD showInfoWithStatus:@"上传失败"];
[SVProgressHUD dismiss];
}];
}