0

全部,我正在使用 RestKit for iOS 将 JPEG 文件上传到我的 Java Web 服务。我提到了这个

开发文件上传网络服务的教程,当我通过我的网络浏览器使用它时它工作得很好。

但是,当我尝试使用 RESTKit 上传文件时,在 TOMCAT 日志中我得到 HTTP/1.1 200 213 状态代码并且我的文件没有上传。

这是我的 RESTKit 代码:

 RKObjectManager* manager = [RKObjectManager sharedManager]; 
RKObjectLoader* objectLoader = [manager objectLoaderWithResourcePath:@"/fileuploaded" delegate:self];
objectLoader.method = RKRequestMethodPOST;

UIImage *image = [UIImage imageNamed:@"rental_car_bill.jpeg"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0); 
// attach image 
RKParams *params = [RKParams paramsWithDictionary:(NSDictionary*)objectLoader.params]; 
RKParamsAttachment *attachment = [params setData:imageData 
                                        MIMEType:@"image/jpeg" forParam:@"photo"]; 
attachment.fileName = @"samplejpeg";
objectLoader.params = params;
objectLoader.targetObject = self;
[objectLoader send];

编辑: 上面的实现确实有效并且文件确实被上传了。但是,在委托方法中: - (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects

超出此范围后,我的应用程序在 [RKObjectLoader dealloc] 处崩溃;

4

1 回答 1

0

使用restkit上传图片我使用以下方法,我更喜欢使用块来避免我的应用程序出现一些问题,也许这样可以避免崩溃:

- (void) upload: (KFMedia *) pic onLoad:(RKObjectLoaderDidLoadObjectBlock) loadBlock onError:(RKRequestDidFailLoadWithErrorBlock)failBlock{

    //pic.image returns an UIImage
    RKParams* imageParams = [RKParams params];
    NSData* imageData = UIImageJPEGRepresentation(pic.image, 0.7f);
    [imageParams setData:imageData MIMEType:@"image/jpg" forParam:@"FileUpload"];
    NSString *resourcePath = @"/api/upload/";


    //My API Server will return a JSON that represents my KFMedia Class after uploading the image, so here I get the propper mapping for that
    RKObjectMapping *mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[KFMedia class]];

    [[RKObjectManager sharedManager] loadObjectsAtResourcePath:resourcePath usingBlock:^(RKObjectLoader *loader) {
        loader.method = RKRequestMethodPOST;
        loader.params = imageParams;
        [self settingsForLoader:loader withMapping:mapping onLoad:loadBlock onError:failBlock];

    }];

}

- (void) settingsForLoader: (RKObjectLoader *) loader withMapping: (RKObjectMapping *) mapping onLoad:(RKObjectLoaderDidLoadObjectBlock) loadBlock onError:(RKRequestDidFailLoadWithErrorBlock)failBlock{

    loader.objectMapping = mapping;
    loader.delegate = self;
    loader.onDidLoadObject = loadBlock;
    loader.onDidFailWithError = ^(NSError * error){
        NSLog(@"%@",error);
    };
    loader.onDidFailLoadWithError = failBlock;
    loader.onDidLoadResponse = ^(RKResponse *response) {
        [self fireErrorBlock:failBlock onErrorInResponse:response];
    };

}
于 2012-05-28T06:54:59.160 回答