iOS-上傳相冊圖片

注:用的AFNetworking版本低于3.0

1呼胚、遵守協(xié)議UIImagePickerControllerDelegate,UINavigationControllerDelegate
2观蓄、首先創(chuàng)建按鈕,添加點(diǎn)擊事件

//點(diǎn)擊事件
- (void)onTapSecondCell
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"打開相機(jī)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf takePhoto];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"打開相冊" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf localPhoto];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:^{
            NSLog(@"取消準(zhǔn)備照片");
        }];
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}
//打開相機(jī)
- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])//相機(jī)
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        
        [self presentViewController:picker animated:YES completion:^{
            NSLog(@"調(diào)取相機(jī)成功");
        }];
    }
    else{
        NSLog(@"模擬器情況下無法打開");
    }
}
//打開相冊
- (void)localPhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])//相冊
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{
            NSLog(@"調(diào)取相冊成功");
        }];
    }
    else{
        NSLog(@"相冊打不開應(yīng)該是出問題了");
    }
}

實(shí)現(xiàn)協(xié)議方法

//當(dāng)選擇一張圖片后進(jìn)入到這個協(xié)議方法里
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //當(dāng)選擇的類型是圖片
    if ([type isEqualToString:@"public.image"])
    {
        //先把圖片轉(zhuǎn)成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
     
        NSData *data1;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data1 = UIImageJPEGRepresentation(image, 1);
        }
        else
        {
            data1 = UIImagePNGRepresentation(image);
        }
        //圖片保存的路徑
        //這里將圖片放在沙盒的documents文件夾中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //把剛剛圖片轉(zhuǎn)換的data對象拷貝至沙盒中 并保存為image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data1 attributes:nil];
        //得到選擇后沙盒中圖片的完整路徑
        NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        long long abc = [self fileSizeAtPath:filePath];
        if (abc < 1024000) {
            _headerImage = image;
        }
        else {
            //如果圖片尺寸過大則壓縮
            UIImage *small = [Help imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width/4, image.size.height/4)];
            NSData *data;
            if (UIImagePNGRepresentation(small) == nil)
            {
                data = UIImageJPEGRepresentation(small, 0.25);
            }
            else
            {
                data = UIImagePNGRepresentation(small);
            }     
            [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
            _headerImage = small;
        }
        //關(guān)閉相冊界面
        [picker dismissViewControllerAnimated:YES completion:^{
            NSLog(@"關(guān)閉相冊界面");
        }];
        [self.tableView reloadData];
    }
}
//判斷文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        NSLog(@"您取消了選擇圖片222");
    }];
}

選中圖片上傳

- (void)postData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    [manage POST:Health_GetReportPic parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //上傳圖片
        NSData *data = UIImageJPEGRepresentation(_headerImage, 1.0);
        [formData appendPartWithFileData:data name:@"report_pic_path" fileName:@"image.png" mimeType:@"png"];
//name-->對應(yīng)數(shù)據(jù)庫存儲的字段  
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([dict[@"message"] isEqualToString:@"數(shù)據(jù)插入成功"]) 
        {
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            [weakSelf addAlertControllerWithMessage:@"上傳成功"];
            //沙盒中圖片的完整路徑
            NSString *string1 = [NSHomeDirectory() stringByAppendingString:@"/Documents/image.jpg"];
            NSFileManager *fileManage = [NSFileManager defaultManager];
            [fileManage removeItemAtPath:string1 error:nil];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error.localizedDescription);
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [weakSelf addAlertControllerWithMessage:@"上傳失敗"];
    }];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末暇韧,一起剝皮案震驚了整個濱河市蚀狰,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖敦姻,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異歧杏,居然都是意外死亡镰惦,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進(jìn)店門犬绒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來旺入,“玉大人,你說我怎么就攤上這事懂更≌R担” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵沮协,是天一觀的道長龄捡。 經(jīng)常有香客問我,道長慷暂,這世上最難降的妖魔是什么聘殖? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任晨雳,我火速辦了婚禮,結(jié)果婚禮上奸腺,老公的妹妹穿的比我還像新娘餐禁。我一直安慰自己,他們只是感情好突照,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布帮非。 她就那樣靜靜地躺著,像睡著了一般讹蘑。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上陨舱,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天游盲,我揣著相機(jī)與錄音益缎,去河邊找鬼然想。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的杖刷。 我是一名探鬼主播滑燃,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼表窘,長吁一口氣:“原來是場噩夢啊……” “哼甜滨!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起昂验,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤既琴,失蹤者是張志新(化名)和其女友劉穎甫恩,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體奖慌,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡升薯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年涎劈,在試婚紗的時候發(fā)現(xiàn)自己被綠了蛛枚。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蹦浦。...
    茶點(diǎn)故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡盲镶,死狀恐怖蝌诡,靈堂內(nèi)的尸體忽然破棺而出浦旱,到底是詐尸還是另有隱情,我是刑警寧澤宣蠕,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布抢蚀,位于F島的核電站镰禾,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏谷饿。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望听怕。 院中可真熱鬧虑绵,春花似錦、人聲如沸声搁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽法挨。三九已至,卻和暖如春惰爬,著一層夾襖步出監(jiān)牢的瞬間惫企,已是汗流浹背狞尔。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工偏序, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留胖替,地道東北人。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓好芭,卻偏偏與公主長得像舍败,于是被迫代替她去往敵國和親敬拓。 傳聞我的和親對象是個殘疾皇子乘凸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內(nèi)容