宽容他人,放过自己。

同时上传多张图片_可重用版本

Posted on By anchoriteFili

#warning 这个过程,创建新增字典,字典懒加载,创建向字典中加数据方法,从别处接收数据,将接收来的数据上传
@property (nonatomic,retain) NSMutableDictionary *addImageInformationDic; //新增图片信息字典

#pragma mark addImageInformationDic新增图片信息懒加载
- (NSMutableDictionary *)addImageInformationDic {
    if (!_addImageInformationDic) {
        _addImageInformationDic = [NSMutableDictionary dictionary];
    }
    return _addImageInformationDic;
}

#pragma mark 将图片位置,二进制数据和文件路径添加到addImageInformationDic中
- (void)dictionaryWithphotoIndex:(NSNumber *)photoIndex imageData:(NSData *)imageData filePath:(NSString *)file andPhotoName:(NSString *)photoName {
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:imageData,@"imageData",file,@"filePath",photoName,@"photoName", nil];
    [self.addImageInformationDic setObject:dic forKey:photoIndex];
}

#pragma mark 从照相机或者图库中获取的图片进行处理
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]&& picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
        mineImage = nil;
        mineImage = [info objectForKey:UIImagePickerControllerEditedImage];
        UIImageWriteToSavedPhotosAlbum(mineImage, self, nil, nil);
    }
    //当选择的类型是图片
    if ([mediaType isEqualToString:@"public.image"])
    {
        //把剪切后的图片转化成NSData
        mineImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        
        if (UIImagePNGRepresentation(mineImage) == nil)
        {
            imdata = UIImageJPEGRepresentation(mineImage, 1.0);
        }
        else
        {
            imdata = UIImagePNGRepresentation(mineImage);
        }
        _isSavePicture = YES;
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        float kCompressionQuality = 0.3;
        imdata = UIImageJPEGRepresentation(mineImage, kCompressionQuality);
        
        [_dataArray addObject:imdata];
        NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
        formatter1.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter1 stringFromDate:[NSDate date]];
        //对图片的位置和名字进行赋值
        PhotoName = [NSString stringWithFormat:@"%@.jpg", str];
        PhotoIndex = [NSNumber numberWithInteger:tag1-1000];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        filePath = [DocumentsPath stringByAppendingPathComponent:PhotoName];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:filePath contents:imdata attributes:nil];
        
#warning 将新增加的图片信息全部传给赋值给新增信息字典
        [self dictionaryWithphotoIndex:PhotoIndex imageData:imdata filePath:filePath andPhotoName:PhotoName];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        switch (tag1) {
            case 1001:
                //将选取的图片放到头像上
                photoCell.secondImageView.image = mineImage;
                break;
            case 1002:
                //将选取的图片放到头像上
                photoCell.secondImageView.image = mineImage;
               break;
            case 1003:
                //将选取的图片放到头像上
                photoCell.thirthImageView.image = mineImage;
                break;
            case 1004:
                //将选取的图片放到头像上
                photoCell.forthImageView.image = mineImage;
                break;
            case 1005:
                //将选取的图片放到头像上
                photoCell.fifthImageView.image = mineImage;
                break;
            case 1006:
                //将选取的图片放到头像上
                photoCell.sixthImageView.image = mineImage;
                break;
            default:
                break;
        }
        
        NSDictionary * dic = @{@"ImgId":@"-8888",@"PhotoName":PhotoName,@"PhotoLocIndex":PhotoIndex};
        [_jsonArray addObject:dic];
        NSData *jsonStr = [NSJSONSerialization dataWithJSONObject:_jsonArray options:NSJSONWritingPrettyPrinted error:nil];
        
        NSString * StJson = [[NSString alloc]initWithData:jsonStr encoding:NSUTF8StringEncoding];
        _StrJson = StJson;
    }
}

#pragma mark 图片上传功能的实现
- (void)saveBtnClick {
    
    NSLog(@"self.addImageInformationDic ============ %@",self.addImageInformationDic);
    
#pragma mark 这些都是一些固定的部分
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    
    NSNumber *UserID  =[NSNumber numberWithInteger:self.userid];
    NSString *NickName = personalCell.nameTextFile.text;
    NSString *Birthday = birthdayCell.brithdayTextFiled.text;
    if (!Birthday) {
        Birthday = [self getTime];
    }
    
    NSString *t = [BaseViewController millisecondsDifferential];
    NSArray *photoIndexs = [self.addImageInformationDic allKeys];
#pragma mark 下面对变的参数进行赋值
    for (NSNumber *photoIndex in photoIndexs) {
        NSDictionary *dic2 = [self.addImageInformationDic objectForKey:photoIndex];
        NSData *imageData = [[self.addImageInformationDic objectForKey:photoIndex] objectForKey:@"imageData"];
        NSString *fileName = [[self.addImageInformationDic objectForKey:photoIndex]  objectForKey:@"filePath"];
        
        NSString *jiami = [BaseViewController md5:[NSString stringWithFormat:@"%@%@&UserID=%@&NickName=%@&Birthday=%@&PhotoName=%@&PhotoIndex=%@",kSecondTime,t,UserID,NickName,Birthday,dic2[@"photoName"],photoIndex]];
        NSString *jiami1 = [BaseViewController Keymd5:jiami];
        NSString *auth = [BaseViewController md5:jiami1];
        //创建接口参数
        NSDictionary *dic = @{@"t":t,
                              @"auth":auth,
//                            @"file":File,
                              @"UserId":UserID,
                              @"NickName":NickName,
                              @"Birthday":Birthday,
                              @"PhotoName":dic2[@"photoName"],
                              @"PhotoIndex":photoIndex
                              };
        
        NSString *userPhotoUrl = [NSString stringWithFormat:@"%@%@",KTHttp,kUserAllPhoto];
        
        [manager POST:userPhotoUrl parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            //将数据传输到网上
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/Documents"];
        }
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  if (!_letfVC) {
                      _letfVC = [[LeftVC alloc] init];
                  }
                  [_letfVC personHomepage];
                  
              } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  NSLog(@"保存失败!");
              }];
    }
}