使用JSON(HTTP正文)中的NSData上载多部分图像

时间:2016-02-17 15:55:35

标签: ios objective-c web-services multipartform-data

我正在尝试将多部分图像上传到服务器,其中图像转换为NSData,并且此NSdata在JSON字符串中的HTTP正文中发送参数。不幸的是,应用程序崩溃了这条消息:

**'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)'**

我知道问题出在JSON上。示例代码:

-(void) uploadmultipartimage {

    NSString * urlimageupload = [NSString stringWithFormat:@"%@api/mobile_profiles/avatar_upload",URLPrefixCertintell];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlimageupload]];

    NSData *imageData = UIImageJPEGRepresentation(_profileimage, 1.0);

    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:60];
    [request setHTTPMethod:@"PUT"];

    NSString *boundary = @"unique-consistent-string";

    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

    // post body
    NSMutableData *body = [NSMutableData data];

    // add params (all params are strings)
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@\r\n\r\n", @"imageCaption"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", @"Some Caption"] dataUsingEncoding:NSUTF8StringEncoding]];

    // add image data
    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=imageName.jpg\r\n", @"imageFormKey"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    NSDictionary *jsonString = @{@"user":@{@"user_token":[[NSUserDefaults standardUserDefaults] stringForKey:@"user_token"]},@"api_key":APIKey,@"profile":body};

    //***Code Crashes here**//
    NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonString options:0 error:nil];

    //
    // setting the body of the post to the reqeust
    [request setHTTPBody:postData];

    // set the content-length
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if(data.length > 0) {
            //success
        }
    }];

}

1 个答案:

答案 0 :(得分:1)

您需要将数据转换为NSString:

    NSString *g=[[NSUserDefaults standardUserDefaults] stringForKey:@"user_token"];
if (!g) 
    g=@"Default Token";

NSString *base64Body = [body base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

NSDictionary *jsonString = @{@"user":@{@"user_token":g},@"api_key":APIKey,@"profile":base64Body};

然后你总是可以在阅读" user_token"时讨论nil的可能性。

小心,

/安德斯。