您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 圖片上傳實戰:相機選圖、JPEG 壓縮與 AFNetworking 表單上傳

編輯:iOS 相關教學

以下範例示範一條完整的圖片上傳路徑:從相簿或相機取得原圖,壓縮後以 multipart 表單送到伺服器,並處理成功與失敗的提示。

一、選圖完成後的上傳流程

#pragma mark - 選圖完成
- (void)imagePickerController:(UIImagePickerController *)picker
    didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info
{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    self.currentTapCell.photoManageImgView.image = image;

    NSIndexPath *indexPath = [self.baseTable indexPathForCell:self.currentTapCell];
    NSString *key = [NSString stringWithFormat:@"ineed%u%u", indexPath.row, indexPath.section];

    [[NetEngineHelper shareNetEngine]
        postUploadWithUrl:k_uploadPhoto_url
                    image:image
                 fileName:[NSString stringWithFormat:@"%@.png", key]
                 fileType:@"PNG/JPEG/JPG"
                  success:^(id response) {
        if ([response[@"STATUS"] intValue] != 0) {
            NSString *str = response[@"ERRORDESC"] ? response[@"ERRORDESC"] : @"系統異常";
            [AlertHelper shareAlertHelper].onVC = self;
            [AlertHelper shareAlertHelper].alertTitle = str;
            [AlertHelper shareAlertHelper].alertMessage = nil;
            [[AlertHelper shareAlertHelper] alertVcWithSureAction:^(id response) {}];
        } else {
            [AlertHelper shareAlertHelper].onVC = self;
            [AlertHelper shareAlertHelper].alertTitle = @"上傳成功";
            [AlertHelper shareAlertHelper].alertMessage = nil;
            [[AlertHelper shareAlertHelper] alertVcWithSureAction:^(id response) {}];

            if ([self.currentTapCell.photoDescribeLable.text isEqualToString:@"上傳診斷證明"]) {
                [self.successUploadDic setValue:response[@"FILEID"] forKey:@"PROVEID"];
            }
            if ([self.currentTapCell.photoDescribeLable.text isEqualToString:@"上傳病歷首頁"]) {
                [self.successUploadDic setValue:response[@"FILEID"] forKey:@"CASEHOMEID"];
            }
            NSLog(@"上傳結果 %@", response);
        }
    } fail:^(NSError *error) {
        [AlertHelper shareAlertHelper].onVC = self;
        [AlertHelper shareAlertHelper].alertTitle = error.userInfo[@"NSLocalizedDescription"];
        [AlertHelper shareAlertHelper].alertMessage = nil;
        [[AlertHelper shareAlertHelper] alertVcWithSureAction:^(id response) {}];
    }];

    [self dismissViewControllerAnimated:YES completion:^{}];
}

二、封裝上傳方法

/** 上傳檔案 */
- (void)postUploadWithUrl:(NSString *)urlStr
                    image:(UIImage *)image
                 fileName:(NSString *)fileName
                 fileType:(NSString *)fileType
                  success:(Success)success
                     fail:(Faile)fail
{
    NSString *resultStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:
                           [NSCharacterSet URLQueryAllowedCharacterSet]];
    self.success = success;
    self.failer = fail;

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes =
        [NSSet setWithObjects:@"text/html", @"application/json", @"text/plain", nil];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.securityPolicy setAllowInvalidCertificates:YES];

    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;

    [manager POST:resultStr
       parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 關鍵:壓縮品質 0.02
        NSData *imgData = UIImageJPEGRepresentation(image, 0.02);
        [formData appendPartWithFileData:imgData
                                    name:@"FILENAME"
                                fileName:fileName
                                mimeType:fileType];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(responseObject);
        application.networkActivityIndicatorVisible = NO;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(error);
        application.networkActivityIndicatorVisible = NO;
    }];
}

程式碼中有幾處值得逐一檢視:

  • 壓縮品質 0.02 太激進。實務上建議依用途分級,例如 0.8 供預覽、0.5 供一般上傳,並在壓縮前後比較檔案大小,避免畫質劣化到無法辨識(特別是病歷、診斷證明這類需要看清細節的影像,品質 0.02 幾乎不可用)。
  • 先縮尺寸再壓縮。用 UIGraphicsBeginImageContextWithOptions 把長邊限制在 1280~1920px,通常比單純調低壓縮品質更能有效縮小檔案且保留清晰度。
  • acceptableContentTypes 覆蓋順序有問題。範例先設成 JSON serializer,後面又指定 JSON,但前面已用 AFHTTPResponseSerializer 覆寫過,建議只保留一處設定以免混淆。
  • setAllowInvalidCertificates:YES 不該出現在正式環境。關閉憑證驗證等於放棄 HTTPS 的傳輸保護,屬於安全風險,上線前務必移除,改用憑證綁定(pinning)才是正確做法。
  • 網路指示器應以 try/finally 或分散式寫法確保一定會關閉,避免請求提早 return 時轉圈圈不會停。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved