一步步教你如何上传头像

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

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

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


目录
相关文章
|
2月前
|
人工智能 Serverless API
想要一个龙年头像,在线等挺急的
想要一个龙年头像,在线等挺急的
852 52
uniapp上传头像和最多上传9张demo效果(整理)
uniapp上传头像和最多上传9张demo效果(整理)
|
8月前
|
SQL JSON 前端开发
上传头像【项目 商城】
上传头像【项目 商城】
29 0
|
8月前
|
自然语言处理 Python Windows
|
10月前
|
小程序 JavaScript 前端开发
微信小程序上传头像和昵称持久化保存
微信小程序上传头像和昵称持久化保存
760 0
|
搜索推荐 前端开发 API
这个验证码合集,从图形到行为验证,你想要的都有-KgCaptcha
凯格行为验证码 - KgCaptcha,采用业界通用的API接口方式,对接轻松简单,即可享受带来的产品服务能力。自定义样式及风控等级,完全个性化的设置,与你的应用完美融合。
这个验证码合集,从图形到行为验证,你想要的都有-KgCaptcha
|
JavaScript 前端开发
【Axure教程】上传本地图片
【Axure教程】上传本地图片
【Axure教程】上传本地图片
|
小程序 前端开发 开发者
Hbuilder中微信小程序上传多图的案例分享
Hbuilder中微信小程序上传多图的案例分享
Hbuilder中微信小程序上传多图的案例分享
|
弹性计算 开发者 云计算
将表白页面上传到服务器|学习笔记
快速学习将表白页面上传到服务器
81 0
将表白页面上传到服务器|学习笔记
|
弹性计算 Linux
将表白页面上传到服务器
一、安装FileZilla 二、上传
将表白页面上传到服务器