iOS form表单上传图片

使用AFNetworking的方法

//压缩图片
    NSData *imageData = UIImageJPEGRepresentation(image,0);
    //沙盒,准备保存的图片地址和图片名称
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    formatter.dateFormat=@"yyyyMMddHHmmss";
    NSString *str=[formatter stringFromDate:[NSDate date]];
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpeg",str]];
    //将图片写入文件中
    [imageData writeToFile:fullPath atomically:NO];
    //通过路径获取到保存的图片,可以在主界面上的image进行预览
    UIImage *saveImage = [[UIImage alloc]initWithContentsOfFile:fullPath];
    
    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];
    gron_User;
    gron_self;
    [manager.requestSerializer setValue:gron_Token forHTTPHeaderField:gron_AFNKEY];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"1" forKey:@"flagFace"];
    [dict setObject:@"1" forKey:@"zipFlag"];
    [dict setObject:fullPath forKey:@"file"];
    
    NSString *url = @"https://xxx.com";
    
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    gron_hub;
    
    [manager POST:url parameters:dict constructingBodyWithBlock:^(id  _Nonnull formData) {
      /* 该方法参数
         appendPartWithFileData:要上传的照片二进制流
         name:对应后台要上传接口的参数名
         fileName:要保存的文件名
         mimeType:要保存到服务器的文件类型
         */
        [formData appendPartWithFileData:imageData name:@"file" fileName:fullPath mimeType:@"image/jpg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hub hideAnimated:YES];
        DSLog(@"上传成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hub hideAnimated:YES];
        DSLog(@"上传失败");
    }];

你可能感兴趣的:(iOS form表单上传图片)