iOS上传头像

使用AFNetworking2.6.3上传头像
其实原理很简单,首先图片也是数据,是数据就可以像其他数据上传,不过时体积大一邪恶而已;其次图片封装到请求头的形式,必须和后端商量好接口的形式。

- (void)updatePortrait
{
    MBProgressHUD *HUD = [Utils createHUD];
    HUD.label.text = @"正在上传头像";

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager OSCJsonManager];
    
    NSString *strUrl = [NSString stringWithFormat:@"%@%@", OSCAPI_V2_PREFIX, OSCAPI_USER_EDIT_PORTRAIT];
    
    [manager POST:strUrl
parameters:@{@"uid":@([Config getOwnID])}
constructingBodyWithBlock:^(id formData) {
        if (_image) {
            [formData appendPartWithFileData:[Utils compressImage:_image]
                                        name:@"portrait"
                                    fileName:@"img.jpg"
                                    mimeType:@"image/jpeg"];
        }
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 1) {
            _myInfo = [OSCUserItem osc_modelWithDictionary:responseObject[@"result"]];
            
            HUD.mode = MBProgressHUDModeCustomView;
            HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HUD-done"]];
            HUD.label.text = @"头像更新成功";
        } else {
            HUD.label.text = @"头像更换失败";
        }
        [HUD hideAnimated:YES afterDelay:1];
        [Config updateNewProfile:_myInfo];
        
        [self refreshHeaderView];
        [self.refreshControl endRefreshing];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        HUD.mode = MBProgressHUDModeCustomView;
        HUD.label.text = @"网络异常,头像更换失败";
        
        [HUD hideAnimated:YES afterDelay:1];
    }];
    
}

你可能感兴趣的:(iOS上传头像)