ios - 上传图片(MultipartFormData)请求objctiveC

标签 ios objective-c post multipartform-data

我正在尝试发送帖子请求。
这是我的尝试:

-(void)Test{

NSDictionary * orderMasterDict = @{@"distributorId":@10000,
                                   @"fieldUsersId": @3,
                                   @"itemId":@0,@"orderMatserId":@56358                                                 };

Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];

NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];

NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:jsonString2 forKey:@"orderMaster"];
[_params setObject:jsonString forKey:@"orderDetails"];
[_params setObject:[NSString stringWithFormat:@"3"] forKey:@"userId"];
[_params setObject:[NSString stringWithFormat:@"ALRAISLABS"] forKey:@"subsCode"];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = @"imageUpload";

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@"http://192.168.0.102:8080/Demo/Test/create"];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

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

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

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(_uploadImageView.image, 0.6);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] 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", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

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

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

// set URL
[request setURL:requestURL];


NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if (error){
        NSLog(@"ERROR :",error);
    }else{
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);
        if ([httpResponse statusCode] == 200) {
            NSLog(@"StatusCode : %ld",(long)[httpResponse statusCode]);
        }else{
            NSLog(@"Error");
        }
    }
}] resume];}

如何发出 multipartFormData 请求? 我尝试用谷歌搜索,找不到任何适合这种情况的答案,并想了想。请帮助我找到正确的解决方案。 提前致谢。

最佳答案

首先,您在 NSData 中更改图像,然后在 AFNetworking 的帮助下,您可以发布您的图像。

NSData *data = UIImagePNGRepresentation(yourImage);
imageData = [data base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength]; 

然后使用此代码:

NSMutableDictionary *finaldictionary = [[NSMutableDictionary alloc] init];
[finaldictionary setObject:imageData forKey:@"image"];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST: [NSString stringWithFormat: @"%@%@", IQAPIClientBaseURL, kIQAPIImageUpload] parameters: finaldictionary constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) { }
    progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"Success response=%@", responseObject);
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingAllowFragments error: nil];
        NSLog(@"%@", responseDict);
    }
    failure: ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Errorrrrrrr=%@", error.localizedDescription);
    }
];

关于ios - 上传图片(MultipartFormData)请求objctiveC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42158191/

相关文章:

iphone - 使用名称截断 NSString

php - 使用 PHP 获取我必须登录才能到达的 URL 的源代码

mysql - 从我的 .csv URL 列表中删除 Wordpress 帖子

iOS7 - 为什么当我以 iOS 6 或 7 的方式查看时页面元素会发生变化

ios - 设置导航栏按钮的目标

objective-c - 游戏中心特定配对

objective-c - Facebook 图表 API : audio share

ios - 平移速度计算以快速执行不同的任务

ios - iOS 应用程序不同本地化的不同二进制文件

java - java中如何接收文件(servlet/jsp)