美文网首页
上传图片到后台数据库(做植物系统的笔记)

上传图片到后台数据库(做植物系统的笔记)

作者: 奕珃 | 来源:发表于2018-01-08 17:33 被阅读0次

    这儿的需求为两个固定的图片数组,可以根据需要进行修改

    #FileUpLoad.h

    /**    *  上传带图片的内容,允许多张图片上传(URL)POST  

     *   

    *  @param url          传url    

    *  @param images       要上传的图片数组(注意数组内容需是图片)   

    *  @param parameter    图片数组对应的参数 可以为nil    

    *  @param parameters   其他参数字典 可以为nil   

    *  @param succeedBlock 成功的回调   

    *  @param failedBlock  失败的回调    */

    -(void)startMultiPartUploadTaskWithURL:(NSString *)url  imagesArray:(NSArray *)images  parameterOfimages:(NSArray *)parameter   parametersDict:(NSDictionary *)parameters succeedBlock:(void (^)(NSDictionary *dict))succeedBlock  failedBlock:(void (^)(NSError *error))failedBlock;

    #FileUpLoad.m

    - (void)startMultiPartUploadTaskWithURL:(NSString *)url imagesArray:(NSArray *)images parameterOfimages:(NSArray *)parameter parametersDict:(NSDictionary *)parameters succeedBlock:(void (^)(NSDictionary *dict))succeedBlock failedBlock:(void (^)(NSError *error))failedBlock{

            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

                 //以下三项manager的属性根据需要进行配置      //                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

            manager.requestSerializer.timeoutInterval = 10;

            manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];             manager.securityPolicy.allowInvalidCertificates = YES;             [manager.securityPolicy setValidatesDomainName:NO];                  manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/xml",@"text/plain", @"application/javascript", @"image/*", nil];

             manager.requestSerializer = [AFHTTPRequestSerializer serializer];             manager.responseSerializer = [AFHTTPResponseSerializer serializer];              [manager POST:url parameters:parameters constructingBodyWithBlock:^(id  _Nonnull formData) {

                    int i = 0;

                     //根据当前系统时间生成图片名称

                     NSDate *date = [NSDate date];

                     NSDateFormatter *formatter = [[NSDateFormatter alloc]init];                                  [formatter setDateFormat:@"yyyyMMddHHmmss"];

                     NSString *dateString = [formatter stringFromDate:date];

                              //习性文件数组        

                    for (int a = 0;a <[images[0] count]; a++) {

                        if ([images[0][a] isKindOfClass:[UIImage class]]) {//判断是否为UIImage,如果不是图片,压缩会报错! 

                        UIImage* image = images[0][a];

                        NSString *fileName = [NSString stringWithFormat:@"%@%d.png",dateString,i];

                         NSData *imageData = [self imageData:image];                                                      [formData appendPartWithFileData:imageData name:parameter[0] fileName:fileName mimeType:@"image/jpg/png/jpeg"];

                }

            }

            //应用文件数组

            for (int a = 0;a <[images[1] count]; a++) {

                if ([images[1][a] isKindOfClass:[UIImage class]]) {

                    UIImage* image = images[1][a];

                    NSString *fileName = [NSString stringWithFormat:@"%@%d.png",dateString,i];

                    NSData *imageData = [self imageData:image];

                   [formData appendPartWithFileData:imageData name:parameter[1] fileName:fileName mimeType:@"image/jpg/png/jpeg"];

                }

            }

           } progress:^(NSProgress * _Nonnull uploadProgress) {

    NSLog(@"进度条");

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

                     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

            NSLog(@"common post responseObject = %@", responseObject);                 NSLog(@"common post json = %@", dict);

                     succeedBlock(dict);

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

                      failedBlock(error);

                      NSLog(@"error == %@",error);

                         }

                 }];

    }


    压缩图片

    //压缩图片至100k以下

    - (NSData *)imageData:(UIImage *)myimage{

        NSData *data = UIImageJPEGRepresentation(myimage, 1.0);

        if (data.length>100*1024) {

            if (data.length>1024*1024) {//1M以及以上

                data = UIImageJPEGRepresentation(myimage, 0.1);

            } else if (data.length>512*1024) {//0.5M-1M

                data = UIImageJPEGRepresentation(myimage, 0.5);

            } else if (data.length>200*1024) {//0.25M-0.5M

                data = UIImageJPEGRepresentation(myimage, 0.9);

            }

        }

        return data;

    }


    调用 

    NSDictionary *paramDic = @{@"id":self.plantDetailModel.id,                                                                              @"name":nameAndStatusModel.name,                                                                              @"typeId":nameAndStatusModel.statusID,                                                                        @"shapeDesc":infoModelOne.describe,                                                                              @"applyDesc":infoModelTwo.describe};

    NSArray *imags = @[infoModelOne.imageArr, infoModelTwo.imageArr];

    NSArray *desc = @[@"shapeFileGroup", @"applyFileGroup"];        

    FileUpLoad *file = [[FileUpLoad alloc] init];        

    [file startMultiPartUploadTaskWithURL:[NSString stringWithFormat:@"%@%@",MAINURL, URL] imagesArray:imags parameterOfimages:desc parametersDict:paramDic succeedBlock:^(NSDictionary *dict) {

        NSLog(@"dict  = %@", dict);

    } failedBlock:^(NSError *error) {

        NSLog(@"error  = %@", error);

    }];

    相关文章

      网友评论

          本文标题:上传图片到后台数据库(做植物系统的笔记)

          本文链接:https://www.haomeiwen.com/subject/glbbnxtx.html