iOS AFNetworking 上传多张图片

来源:互联网 发布:知乎网址 编辑:程序博客网 时间:2024/05/27 00:45

- (void)someViewController:(SomeViewController *)someViewController sendToAnotherVCWithName:(NSString *)name andIDNum:(NSString *)idNum {

    NSLog(@"名字:%@和身份证号:%@", name, idNum);

    // ----------------------------上传图片----

    /*

     此段代码如果需要修改,可以调整的位置

     1. upload.php改成网站开发人员告知的地址

     2. name改成网站开发人员告知的字段名

     */

    // 查询条件

    NSDictionary *dic = [NSDictionarydictionaryWithObjectsAndKeys:name,@"name", idNum, @"idNumber",nil];

    

    // 基于AFN3.0+封装的HTPPSession句柄

    AFHTTPSessionManager *manager = [AFHTTPSessionManagermanager];

    manager.requestSerializer.timeoutInterval =20;

    manager.responseSerializer.acceptableContentTypes = [NSSetsetWithObjects:@"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:dicconstructingBodyWithBlock:^(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);

        

    }];

}





原创粉丝点击