Ios 上载图像(MultipartFormData)请求objctiveC
我正在尝试发送post请求。Ios 上载图像(MultipartFormData)请求objctiveC,ios,objective-c,post,multipartform-data,Ios,Objective C,Post,Multipartform Data,我正在尝试发送post请求。 以下是我的尝试: -(void)Test{ NSDictionary * orderMasterDict = @{@"distributorId":@10000, @"fieldUsersId": @3, @"itemId":@0,@"orderMatserId":@56358
以下是我的尝试:
-(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);
}
];
NSMutableDictionary*finaldictionary=[[NSMutableDictionary alloc]init];
[finaldictionary setObject:imageData forKey:@“image”];
AFHTTPSessionManager*manager=[AFHTTPSessionManager-manager];
manager.responseSerializer=[AFHTTPResponseSerializer序列化程序];
[manager POST:[NSString stringWithFormat:@“%@%”,IQAPIClientBaseURL,kIQAPIImageUpload]参数:finaldictionary constructingBodyWithBlock:^(id formData){
进度:无成功:^(NSURLSessionDataTask*\u非空任务,id\u可空响应对象){
NSLog(@“成功响应=%@”,响应对象);
NSDictionary*responseDict=[NSJSONSerialization JSONObject WithData:responseObject选项:NSJSONReadingAllowFragments错误:nil];
NSLog(@“%@”,响应指令);
}
失败:^(NSURLSessionDataTask*_可空任务,NSError*_非空错误){
NSLog(@“Errorrrrrrr=%@”,error.localizedDescription);
}
];
使用阿拉莫菲尔
-(void)CreateOrder{
NSString * urlString = [NSString stringWithFormat:@"YOUR URL"
NSDictionary * orderMasterDict = @{@"distributorId":stakeholderID,
@"fieldUsersId": userID,
@"itemId":@0,@"orderMatserId":@0 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSDictionary * consumerDetails = @{@"consumerName":Globals.PatientName,@"consumerReferenceId":Globals.PatientID,@"notes":Globals.PatientNotes,@"cunsumerContacNumber":@"456464654654"};
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];
//retrieving userId from UserDefaults
prefs = [NSUserDefaults standardUserDefaults];
NSString * userIdString = [prefs stringForKey:@"userID"];
NSDictionary *parameters = @{@"orderMaster": jsonString2, @"orderDetails" : jsonString ,@"userId" : userIdString,@"subsCode" : @"ABC_MDENT"};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//For adding Multiple images From selected Images array
int i = 0;
for(UIImage *eachImage in selectedImages)
{
UIImage *image = [self scaleImage:eachImage toSize:CGSizeMake(480.0,480.0)];
NSData *imageData = UIImageJPEGRepresentation(image,0.3);
[formData appendPartWithFileData:imageData name:@"imageUpload" fileName:[NSString stringWithFormat:@"file%d.jpg",i ] mimeType:@"image/jpeg"];
i++;
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(@"responseObject : %@",responseObject);
if (error) {
NSlog(@"error")
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == 200) {
resposeStatusCode = [responseObject objectForKey:@"statusCode"];
}else{
NSLog(@"requestError");
}
}
}];
[uploadTask resume]; }
-(无效)CreateOrder{
NSString*urlString=[NSString stringWithFormat:@“您的URL”
NSDictionary*orderMasterDict=@{@“distributorId”:StateHolderId,
@“fieldUsersId”:用户ID,
@“itemId”:@0,@“orderMatserId”:@0};
Globals.OrderDetailsArray=[NSMutableArray阵列WithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucentcy,nil];
NSDictionary*consumerDetails=@{“consumerName”:Globals.PatientName,@“consumerReferenceId”:Globals.PatientID,@“notes”:Globals.PatientNotes,@“CUNSumerContactNumber”:@“45646654654”};
NSData*postData=[NSJSONSerialization dataWithJSONObject:Globals.orderDetailsRay选项:NSJSONWriting预打印错误:nil];
NSData*postData2=[NSJSONSerialization dataWithJSONObject:orderMasterDict选项:nsjsonwritingprettyptederror:nil];
NSString*jsonString2=[[NSString alloc]initWithData:postData2编码:NSUTF8StringEncoding];
NSString*jsonString=[[NSString alloc]initWithData:postData编码:NSUTF8StringEncoding];
//从UserDefaults检索userId
prefs=[NSUserDefaults standardUserDefaults];
NSString*userIdString=[prefs stringForKey:@“userID]”;
NSDictionary*参数=@{@“orderMaster”:jsonString 2、@“orderDetails”:jsonString、@“userId”:userIdString、@“subcode”:“ABC\u MDENT”};
NSMutableURLRequest*request=[[AFHTTPRequestSerializer]multipartFormRequestWithMethod:@“POST”URLString:URLString参数:参数constructingBodyWithBlock:^(id formData){
//用于从选定图像阵列中添加多个图像
int i=0;
用于(选定图像中的UIImage*每个图像)
{
UIImage*image=[self-scaleImage:eachImage-toSize:CGSizeMake(480.0480.0)];
NSData*imageData=UIIMAGEJPEG表示法(图像,0.3);
[formData appendPartWithFileData:imageData名称:@“imageUpload”文件名:[NSString stringWithFormat:@“文件%d.jpg”,i]mimeType:@“图像/jpeg”];
i++;
}
}错误:无];
AFURLSessionManager*manager=[[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask*上传任务;
uploadTask=[manager]
uploadTaskWithStreamedRequest:请求
进度:^(NSProgress*_非空上传进度){
dispatch\u async(dispatch\u get\u main\u queue()^{
});
}
completionHandler:^(NSURLResponse*\u非空响应,id\u可空响应对象,NSError*\u可空错误){
NSLog(@“responseObject:%@”,responseObject);
如果(错误){
NSlog(@“错误”)
}否则{
NSHTTPURLResponse*httpResponse=(NSHTTPURLResponse*)响应;
如果([httpResponse statusCode]==200){
resposeStatusCode=[responseObject objectForKey:@“statusCode”];
}否则{
NSLog(@“requestError”);
}
}
}];
[上传任务恢复];}
感谢您的回复。请查看更新后的问题。这就是我正在尝试做的。请帮助我获得正确的结果。提前感谢。。