RestKit 图片上传 [英] RestKit Image Upload

查看:14
本文介绍了RestKit 图片上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RestKit 来驱动与我的 Web 服务器的交互.我正在尝试使用路由将事件对象发布到服务器,并附有图像.代码如下:

I am using RestKit to drive interactions with my web server. I am trying to use routing to POST an Event object to the server with an image attached to it. The code is as follows:

  RKObjectManager *manager = [RKObjectManager sharedManager];

  RKObjectMapping *map = [self eventMapping];
  manager.serializationMIMEType = RKMIMETypeFormURLEncoded;
  map.rootKeyPath = @"event";
  [manager.mappingProvider setSerializationMapping:map forClass:[Event class]];
  [manager.router routeClass:[Event class] toResourcePath:@"/v1/events.json" forMethod:RKRequestMethodPOST];

  [manager postObject:event delegate:self block:^(RKObjectLoader *loader){
    RKObjectMapping *serMap = [[[RKObjectManager sharedManager] mappingProvider] serializationMappingForClass:[Event class]];
    NSError *error = nil;
    NSDictionary *d = [[RKObjectSerializer serializerWithObject:event mapping:serMap] serializedObject:&error];

    RKParams *p = [RKParams paramsWithDictionary:d];
    [p setData:[event imageData] MIMEType:@"image/jpeg" forParam:@"image"];
    loader.params = p;
  }];

如果我使用序列化的 Event 对象创建 RKParams 的实例,然后添加图像数据并将其分配为 RKObjectLoader 的 params 属性,则所有属性都成为一个庞大的序列化字符串.必须有一种方法可以在没有大量字符串序列化的情况下上传图片.

If I create an instance of RKParams using the serialized Event object, then add the image data and assign it as the RKObjectLoader's params property, all the properties become one massive serialized string. There must be a way to upload an image without the massive string serialization.

我也尝试过拥有一个映射到某个属性的 NSData 属性,一路将 UIImage 转换为 NSData,但 RestKit 抱怨它无法映射.以前有人做过吗?

I have also tried having an NSData property that is mapped to some attribute, converting a UIImage into NSData along the way, but RestKit complains that it can't be mapped. Has anyone done this before?

推荐答案

我做了一些非常相似的事情,结果很好.我意识到您的问题是关于为什么 RKObjectSerializer 没有按照您期望的方式工作,但也许它与您的设置有关.我发布我的代码是为了给出一个有效的例子.也就是说,在阅读了 RKObjectSerializer 文档之后,我不明白为什么您不能以这种方式初始化 RKParams,而是像我在示例中那样直接设置它们.

I did something very similar and it worked out just fine. I realize your question is about why RKObjectSerializer isn't working the way you expect, but maybe it is something else with your setup. I'm posting my code to give a clean example of something that does work. That said, after reading the RKObjectSerializer documentation, I don't see why you couldn't initialize your RKParams that way instead of setting them directly as I do in my example.

路由器设置:

RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:kApiUrlBase];
[objectManager.router routeClass:[PAPetPhoto class] toResourcePath:@"/pet/uploadPhoto" forMethod:RKRequestMethodPOST];

映射设置:

RKObjectMapping *papetPhotoMapping = [RKObjectMapping mappingForClass:[PAPetPhoto class]];
[papetPhotoMapping mapKeyPath:@"id" toAttribute:@"identifier"];
[papetPhotoMapping mapAttributes:@"accountId", @"petId", @"photoId", @"filename", @"contentType", nil];
[objectManager.mappingProvider addObjectMapping:papetPhotoMapping];
[objectManager.mappingProvider setSerializationMapping:[papetPhotoMapping inverseMapping] forClass:[PAPetPhoto class]];
[objectManager.mappingProvider setMapping:papetPhotoMapping forKeyPath:@"petPhoto"];

帖子:(请注意,因为我在块中构建了所有参数,所以我的对象只是一个虚拟实例,用于触发正确的路由和映射器).

The post: (notice since I built up all my params in the block my object is just a dummy instance to trigger the proper routing and mapper).

    PAPetPhoto *photo = [[PAPetPhoto alloc] init];
    [[RKObjectManager sharedManager] postObject:photo delegate:self block:^(RKObjectLoader *loader){

        RKParams* params = [RKParams params];
        [params setValue:pet.accountId forParam:@"accountId"];
        [params setValue:pet.identifier forParam:@"petId"];
        [params setValue:_photoId forParam:@"photoId"];
        [params setValue:_isThumb ? @"THUMB" : @"FULL" forParam:@"photoSize"];
        [params setData:data MIMEType:@"image/png" forParam:@"image"];

        loader.params = params;
    }];

服务器端点(Java、Spring MVC)

Server endpoint (Java, Spring MVC)

    @RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> handleFormUpload(@RequestParam("accountId") String accountId,
                                    @RequestParam("petId") String petId,
                                    @RequestParam("photoId") String photoId,
                                    @RequestParam("photoSize") PhotoSizeEnum photoSize,
                                    @RequestParam("image") Part image) throws IOException {

        if (log.isTraceEnabled()) 
            log.trace("uploadPhoto. accountId=" + accountId + " petId=" + petId + " photoId=" + photoId + " photoSize=" + photoSize);

        PetPhoto petPhoto = petDao.savePetPhoto(accountId, petId, photoId, photoSize, image);

        Map<String, Object> map = GsonUtils.wrapWithKeypath(petPhoto, "petPhoto");
        return map;
    }

服务器响应 JSON(注意与映射设置对应的petPhoto"的 keyPath):

Server response JSON (note the keyPath of "petPhoto" that corresponds to the mapping setup):

{
    petPhoto =     {
        accountId = 4ebee3469ae2d8adf983c561;
        contentType = "image/png";
        filename = "4ebee3469ae2d8adf983c561_4ec0983d036463d900841f09_3FED4959-1042-4D8B-91A8-76AA873851A3";
        id = 4ee2e80203646ecd096d5201;
        petId = 4ec0983d036463d900841f09;
        photoId = "3FED4959-1042-4D8B-91A8-76AA873851A3";
    };
}

代表:

- (void) objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object {

    if ([objectLoader wasSentToResourcePath:@"/pet/uploadPhoto"]) {
       PAPetPhoto *photo = (PAPetPhoto*)object;
    }
}

这篇关于RestKit 图片上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆