iOS AFNetworking 3.0+ 上傳多張圖片

- (void)someViewController:(SomeViewController *)someViewController sendToAnotherVCWithName:(NSString *)name andIDNum:(NSString *)idNum {
    NSLog(@"名字:%@ 和身份證號:%@", name, idNum);
    // ----------------------------上傳圖片----
    /*
     此段代碼如果需要修改,可以調整的位置
     1. 把upload.php改成網站開發人員告知的地址
     2. 把name改成網站開發人員告知的字段名
     */
    // 查詢條件
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", idNum, @"idNumber", nil];

    // 基于AFN3.0+ 封裝的HTPPSession句柄
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    // 在parameters里存放照片以外的對象
    [manager POST:@"http://www.example.com/Project/upload.php" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // formData: 專門用于拼接需要上傳的數據,在此位置生成一個要上傳的數據體
        // 這里的_photoArr是你存放圖片的數組
        for (int i = 0; i < _photosArr.count; i++) {

            UIImage *image = _photosArr[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);

            // 在網絡開發中,上傳文件時,是文件不允許被覆蓋,文件重名
            // 要解決此問題,
            // 可以在上傳時使用當前的系統事件作為文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 設置時間格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            /*
             *該方法的參數
                 1. appendPartWithFileData:要上傳的照片[二進制流]
                 2. name:對應網站上[upload.php中]處理文件的字段(比如upload)
                 3. fileName:要保存在服務器上的文件名
                 4. mimeType:上傳的文件的類型
             */
            [formData appendPartWithFileData:imageData name:@"upload" fileName:fileName mimeType:@"image/jpeg"]; //
        }

    } progress:^(NSProgress * _Nonnull uploadProgress) {

        NSLog(@"---上傳進度--- %@",uploadProgress);

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"```上傳成功``` %@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"xxx上傳失敗xxx %@", error);

    }];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容