美文网首页很常
iOS AFN上传图片

iOS AFN上传图片

作者: IMKel | 来源:发表于2021-03-02 15:38 被阅读0次

    这些都是笔者项目中使用到的代码,上传图片测试成功

    • 上传单张图片
    // 拍完照,点击使用照片(use photo)按钮时系统会调用该方法
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
    {
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        [self dismissViewControllerAnimated:YES completion:nil];
        
        // 1.上传图片
        NSMutableDictionary *parametersDict = [NSMutableDictionary dictionary];
        parametersDict[@"userId"] = [NSString stringWithFormat:@"%ld", [FKLocalDataManager shareManager].userBasicInfo.id];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        formatter.dateFormat = @"yyyyMMddHHmmss";
        
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        
        parametersDict[@"name"] = fileName;
        
        NSString *urlString = [BASIC_URL stringByAppendingUrlComponent:@"/file/singlefileUpload"];
        
        FKProgressHUD *hud = [FKProgressHUD showHUDAddedTo:self.view title:@"上传中..." model:MBProgressHUDModeText];
        
        [self.manager POST:urlString parameters:parametersDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                hud.detailsLabel.text = [NSString stringWithFormat:@"上传%.1lf%%", uploadProgress.fractionCompleted * 100];
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 1.更新用户基本信息
            [FKLocalDataManager shareManager].userBasicInfo.picUrl = responseObject[@"content"];
            [[FKLocalDataManager shareManager] updateUserBasicInfoWith:[FKLocalDataManager shareManager].userBasicInfo];
            // 2.提示上传成功
            [hud hideAnimated:YES afterDelay:1.0];
            // 3.更新头像
            self.avatarImgV.image = image;
            // 4.将图片存入沙盒中
            [[SDWebImageManager sharedManager] saveImageToCache:image forURL:[NSURL URLWithString:[BASIC_URL stringByAppendingUrlComponent:[FKLocalDataManager shareManager].userBasicInfo.picUrl]]];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [hud hideAnimated:NO];
            
            [NSObject handleExceptionWithError:error];
        }];
        
    }
    
    • 多图片上传
    #pragma mark - 下一步
    - (void)nextStepBtnDidClick:(UIButton *)sender
    {
        if (![self.nameTF hasText])
        {
            [FKProgressHUD showHUDAddedTo:self.view title:@"姓名不能为空" model:MBProgressHUDModeText];
            return;
        }
        
        if (![self.IDCardTF hasText])
        {
            [FKProgressHUD showHUDAddedTo:self.view title:@"身份证不能为空" model:MBProgressHUDModeText];
            return;
        }
        
        if (self.uploadIDCardFrontBtn.imageView.image == nil)
        {
            [FKProgressHUD showHUDAddedTo:self.view title:@"身份证正面照片不能为空" model:MBProgressHUDModeText];
            return;
        }
        
        if (self.uploadIDCardReverseBtn.imageView.image == nil)
        {
            [FKProgressHUD showHUDAddedTo:self.view title:@"身份证反面照片不能为空" model:MBProgressHUDModeText];
            return;
        }
        
        if (self.uploadGroupPhotoBtn.imageView.image == nil)
        {
            [FKProgressHUD showHUDAddedTo:self.view title:@"手持身份证照片不能为空" model:MBProgressHUDModeText];
            return;
        }
        
        // 图片取名称
        NSMutableArray <NSString *> *fileNames = [NSMutableArray array];
        NSTimeInterval timeInterval = [NSDate timeIntervalSinceReferenceDate];
        for (int i = 0; i < 3; i++) {
            NSString *fileName = [NSString stringWithFormat:@"%ld.png", (NSInteger)++timeInterval];
            [fileNames addObject:fileName];
        }
        
        // 图片压缩
        NSMutableArray <NSData *> *images = [NSMutableArray array];
        [images addObject:UIImageJPEGRepresentation(self.uploadIDCardFrontBtn.imageView.image, 0.5)];
        [images addObject:UIImageJPEGRepresentation(self.uploadIDCardReverseBtn.imageView.image, 0.5)];
        [images addObject:UIImageJPEGRepresentation(self.uploadGroupPhotoBtn.imageView.image, 0.5)];
        
        
        NSMutableDictionary *parametersDict = [NSMutableDictionary dictionary];
        parametersDict[@"driverId"] = [FKLocalDataManager shareManager].userId;
        parametersDict[@"chineseName"] = self.nameTF.text;
        parametersDict[@"idCard"] = self.IDCardTF.text;
        parametersDict[@"idCardFrontPic"] = fileNames[0];
        parametersDict[@"idCardBackPic"] = fileNames[1];
        parametersDict[@"idCardHandPic"] = fileNames[2];
        
        NSString *urlString = [BASIC_URL stringByAppendingUrlComponent:@"/driver/update"];
        
        FKProgressHUD *hud = [FKProgressHUD showHUDAddedTo:self.view title:@"上传中..." model:MBProgressHUDModeText];
        
        [self.manager POST:urlString parameters:parametersDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            [formData appendPartWithFileData:images[0] name:@"idCardFrontPic" fileName:fileNames[0] mimeType:@"image/jpeg"];
            [formData appendPartWithFileData:images[1] name:@"idCardBackPic" fileName:fileNames[1] mimeType:@"image/jpeg"];
            [formData appendPartWithFileData:images[2] name:@"idCardHandPic" fileName:fileNames[2] mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                hud.detailsLabel.text = [NSString stringWithFormat:@"上传%.1lf%%", uploadProgress.fractionCompleted * 100];
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (requestResult)
            {
                FKLog(@"responseObject = %@", responseObject);
                // 1.提示上传成功
                hud.detailsLabel.text = @"数据上传成功";
                [hud hideAnimated:YES afterDelay:1];
                hud.completionBlock = ^{
                    // 2.进入下个界面
                    FKAddCarTVC *vc = [[FKAddCarTVC alloc] init];
                    vc.IDCardNo = self.IDCardTF.text;
                    [self.navigationController pushViewController:vc animated:YES];
                };
            }else
            {
                hud.detailsLabel.text = responseObject[@"message"];
                [hud hideAnimated:YES afterDelay:1.0];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [hud hideAnimated:NO];
            
            [NSObject handleExceptionWithError:error];
        }];
    }
    

    相关文章

      网友评论

        本文标题:iOS AFN上传图片

        本文链接:https://www.haomeiwen.com/subject/kprckftx.html