使用Objective-C POST图像/其他参数的多部分/表单数据

时间:2018-12-24 21:38:09

标签: ios objective-c image-uploading multipartform-data

我研究了很多关于如何在iOS上进行多部分/表单数据POST的文章,但没有任何文章真正解释如果有正常参数以及文件上传该怎么办。

我在iOS上使用了multipart / form-data POST,并且编写了以下代码,它正在上传数据,但未上传图像数据

  - (void)postWithImage:(NSDictionary *)dictionary

{

NSString *urlString = [NSString stringWithFormat:@"YourHostString"];

NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = @"----1010101010";

//  define content type and add Body Boundry
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

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

NSEnumerator *enumerator = [dictionary keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;

while ((key = (NSString *)[enumerator nextObject])) {

    if ([key isEqualToString:@"file"]) {

        value = (NSString *)[dictionary objectForKey:key];

        NSData *postData = UIImageJPEGRepresentation([UIImage imageNamed:value], 1.0);
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\nfilename=\"screen.png\"\r\n\r\n",value] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:postData];
    } else {
        value = (NSString *)[dictionary objectForKey:key];

        content_disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key];
        [body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingPrettyPrinted error:&error];
        [body appendData:jsonData];
        //[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];

    }

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

}

//Close the request body with Boundry
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField: @"Content-Length"];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);

}

任何人都可以帮助我了解为什么不上传图像数据的原因

1 个答案:

答案 0 :(得分:0)

我认为您应该先添加@"content-Type",然后再添加真实数据,如下所示:

[body appendData:[@"Content-Type: image/png\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];