一步步教你如何上传头像

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

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

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];
        }];
    }
}


目录
相关文章
|
安全 Linux
Centos 7.x 升级内核
千万不要小瞧这操作。
1554 0
|
安全 Java API
解决 Swagger API 未授权访问漏洞:完善分析与解决方案
Swagger 是一个用于设计、构建、文档化和使用 RESTful 风格的 Web 服务的开源软件框架。它通过提供一个交互式文档页面,让开发者可以更方便地查看和测试 API 接口。然而,在一些情况下,未经授权的访问可能会导致安全漏洞。本文将介绍如何解决 Swagger API 未授权访问漏洞问题。
|
移动开发 前端开发
RN运行项目Error:Unable to resolve module
RN运行项目Error:Unable to resolve module
1538 0
RN运行项目Error:Unable to resolve module
|
12月前
|
人工智能 弹性计算 运维
对话即运维:阿里云 Workbench AI Agent 让云上操作更智能、更高效
阿里云推出Workbench AI Agent模式,通过自然语言交互实现ECS运维自动化。用户无需记忆复杂命令,即可对话式完成软件安装、问题诊断、系统配置等操作,大幅降低上云门槛,提升运维效率,开启智能云上新体验。
|
12月前
|
弹性计算 搜索推荐 应用服务中间件
阿里云服务器租用费用价格表:从入门级配置到企业级高性能收费标准
阿里云服务器优惠汇总:轻量应用服务器200M带宽38元/年起,ECS云服务器2核2G 99元/年,2核4G 199元/年,4核16G 89元/月,8核32G 160元/月,香港轻量25元/月起,GPU服务器低至1681元/月,新老用户同享,续费同价,限时秒杀,配置丰富,适合个人与企业多种应用场景。
2058 4
|
JSON 算法 API
1688拍立淘图片搜索接口全攻略
1688拍立淘图片搜索接口由阿里巴巴提供,支持通过上传图片在1688平台搜索相似商品。该接口基于图像识别技术,具备高精度匹配、丰富商品信息返回、支持多图片格式及可定制化搜索等特点,适用于电商选品、商品溯源和智能购物等场景。开发者需注册获取app_key与app_secret,并通过Python示例代码调用接口,实现图片搜索功能。
1019 23
|
人工智能 Serverless API
评测|全网最强🚀!5min部署满血版DeepSeek,零成本,无需编程!
本文介绍了阿里云提供的四种DeepSeek部署方案,包括基于百炼调用满血版API、基于函数计算部署、基于人工智能平台PAI部署和GPU云服务器部署。通过这些方案,用户可以摆脱“服务器繁忙”的困扰,实现快速部署与使用
4260 3
评测|全网最强🚀!5min部署满血版DeepSeek,零成本,无需编程!
|
JavaScript 前端开发 API
探讨JavaScript动态添加HTML文件的技术
探讨JavaScript动态添加HTML文件的技术
1107 1