一步步教你如何上传头像

简介: 一步步教你如何上传头像

上传头像这一步几乎在所有的应用中都会用到,但是博主发现即使是那些工作一年甚至两年的开发者依然会问这个问题,更别提那些初学者了,虽然网上能找到好多种上传的方法,但是都存在不同程度的误差,要么是不够详细,要么是运行出错,所以博主今天就把自己常用的一种方法拿出来给大家分享一下。

1.png

首先说明下:博主上传采用的是AF3.0,因为博主去掉了项目中的接口,所以,这个Demo中是不能上传成功的,但是效果会有,看官们只需要把自己的url放进去就可以实现上传了。具体的跟着博主慢慢往下看:


第一步:触发操作

  //根据警告知道这个对象在iOS8.3被废弃了,只是依然可以用,在下篇博客中,会针对废弃后的提供的新方法做介绍和使用
    UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Take photos", @"Select picture in phone album",nil];
    actionSheet.delegate=self;
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [actionSheet showInView:self.view];

第二步:选择相册或直接拍照

#pragma mark - 选择手机拍照上传或者手机相册上传
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        //设置选择后的图片可被编辑
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }
    if (buttonIndex==0) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"请使用真机进行测试" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alertView show];
            NSLog(@"模拟其中无法打开照相机,请在真机中使用");
        }
    }
}

第三步:选择一张图片后

#pragma mark - 当在相册选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        //调整图片方向,防止上传后图片方向不对
        [self fixOrientation:image];
        //压缩图片
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSLog(@"图片储存路径:%@",DocumentsPath);
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        //得到选择后沙盒中图片的完整路径
        NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,@"/image.png"];
        NSLog(@"................%@",filePath);
        //表单请求,上传文件
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
        manager.requestSerializer.timeoutInterval = 8;
        /*
         *这里需要特别注意一下,因为没有放具体的上传地址,所以这个上传方式是不成功的,但是方法是没错的,需要替换成正确的上传地址
         */
        [manager POST:[NSString stringWithFormat:@"url"] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            //将图片以表单形式上传
            NSData *data1=[NSData dataWithContentsOfFile:filePath];
            [formData appendPartWithFileData:data1 name:@"headPicFile" fileName:@"headPicFile" mimeType:@"image/png"];
            //关闭相册界面
            [picker dismissViewControllerAnimated:YES completion:nil];
        }progress:^(NSProgress *uploadProgress){
        }success:^(NSURLSessionDataTask *task, id responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"dic:%@",dic);
            //成功后替换新头像
            NSData *data1=[NSData dataWithContentsOfFile:filePath];
            headImageView.image = [UIImage imageWithData:data1];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"%@",[error description]);
            NSLog(@"%@",error);
            //因为没有有效地址,所以肯定是上传失败的,为了表现出效果,此处也替换为新头像
            NSData *data1=[NSData dataWithContentsOfFile:filePath];
            headImageView.image = [UIImage imageWithData:data1];
        }];
    }
}


目录
相关文章
|
前端开发 Java Spring
Spring Boot 实现图片上传并回显
Spring Boot 实现图片上传并回显
|
存储 缓存 弹性计算
2024年阿里云最便宜云服务器出炉:61元、165元、99元、199元
2024年截止目前阿里云最便宜的云服务器已经出炉,轻量应用服务器2核2G3M带宽61元1年、2核4G4M带宽165元1年;云服务器经济型e实例2核2G3M带宽99元1年;云服务器通用算力型u1实例2核4G5M带宽199元1年。除此之外,还有幻兽帕鲁Palworld专用服务器4核16G10M带宽只要26.52元/1个月、79.56元/3个月、149.00元/6个月,8核32G10M带宽只要90.60元/1个月、271.80元/3个月。本文为大家分享2024年阿里云最便宜的各个云服务器。
8406 4
2024年阿里云最便宜云服务器出炉:61元、165元、99元、199元
|
关系型数据库 MySQL Shell
【MySQL系列】- MySQL自动备份详解
【MySQL系列】- MySQL自动备份详解
1091 0
Qt实用技巧:QtCreator编辑区关闭右侧不必要的警告提示
Qt实用技巧:QtCreator编辑区关闭右侧不必要的警告提示
Qt实用技巧:QtCreator编辑区关闭右侧不必要的警告提示
|
8月前
|
Linux
CentOs9 yum源出现404问题
CentOs9-stream yum源出现404问题
|
JavaScript 前端开发 API
基于Vue和Element UI实现前后端分离和交互
基于Vue和Element UI实现前后端分离和交互
758 1
|
Shell 开发工具 git
如何将项目上传到Gitee上
如何将项目上传到Gitee上
497 0
|
监控 数据可视化 搜索推荐
ERP系统中的财务预测与成本分析解析
【7月更文挑战第25天】 ERP系统中的财务预测与成本分析解析
776 0
|
机器学习/深度学习 人工智能 搜索推荐
详细探讨AI在个性化教育平台中学习路径推荐的应用
详细探讨AI在个性化教育平台中学习路径推荐的应用
|
设计模式 移动开发 Java
浅谈交易链路中的一些设计原则&模式
作者对设计原则、模式等学习后,通过本文谈谈自己的感受。
160148 28