如何使用其他一些参数在httpbody for sever中发送Image

时间:2017-08-11 07:16:29

标签: ios objective-c post

我想将一个图像发送到正文中的服务器。图像没有任何参数。带图像我还有一些其他参数要发送。

我使用下面的代码进行上传。此代码的问题我既没有得到错误也没有结果。

请找到代码;

-(void)uploadimage1
{
NSData *imageData = UIImageJPEGRepresentation(_imgOutlet.image, 1.0);
NSString *base64Img = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
 // NSDictionary *parameters = @{@"data":base64Img};

  NSError *error;
 //    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:base64Img
  //                                                       options:nil
  //                                                         error:&error];
 //    
 //    //do some error checking
 //    http://imhsservices.org/IMHS_NEW/api/Image_Base64?AadharCardNo=369369369369.00&UploadDate=2017-05-25&OriginalName=2.jpg&ReportType=Medical
NSString *urlstr = [NSString stringWithFormat:@"http://imhsservices.org/IMHS_NEW/api/Image_Base64?AadharCardNo=%@&UploadDate=%@&ReportType=%@&OriginalName=%@",@"369369369369.00",@"2017-08-11",@"Medical",@"2.jpg"];
NSLog(@"%@",urlstr);
NSURL *url = [NSURL URLWithString:urlstr];
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:base64Img];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"%@",error);
    if (!error) {
        if ([data length]) {
            NSString *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@",jsonResponse);

            //GET RESULT;
           // NSLog(@"A %@", parameters[@"results"]);

        }

    } else {
        NSLog(@"%@", error);
    }
}];
[task resume];
}

i am getting sucess message when i use in post man

你能帮我解决这个问题吗,谢谢快速回复。谢谢你...

2 个答案:

答案 0 :(得分:1)

<强>更新

在你的情况下试试:

NSString *strImage = [base64Img stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];

然后转换为NSData

NSData *data = [strImage dataUsingEncoding:NSUTF8StringEncoding];

然后将data发送到您的httpBody

从服务器使用时检索

NSString *strImageData = [finalImagePath stringByReplacingOccurrencesOfString:@"%2B" withString:@"+"];

Reference

OR (使用分段上传)

您需要为参数和要上传的图像创建边界。

使用此代码段:

#pragma mark - Upload image with params
+ (void)postRestApiWithImage:(NSDictionary *)params withMethod:(NSString *)methodName withImage:(UIImage *)image completion: (void(^)(id result, NSError* error))completionHandler {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSLog(@"%@", params);

        NSString *boundary = [self generateBoundaryString];

        // configure the request

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithFormat:@"%s%@", kbaseUrl, methodName]]];
        [request setHTTPMethod:@"POST"];

        // set content type

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

        // create body

        NSData *httpBody = [self createBodyWithBoundary:boundary parameters:params paths:@[image] fieldName:@"profile_image"];

        request.HTTPBody = httpBody;

        NSURLSession *session = [NSURLSession sharedSession];  // use sharedSession or create your own

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

            if (error) {

                dispatch_async(dispatch_get_main_queue(),^ {

                    if (completionHandler) {

                        completionHandler(nil, error);
                    }
                });

                NSLog(@"error = %@", error);
                return;
            }

            dispatch_async(dispatch_get_main_queue(),^ {

                if (completionHandler) {

                    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; //Make one NSError here

                    // NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    NSLog(@"result = %@", result);

                    completionHandler(result, nil);
                }
            });
        }];
        [task resume];
    });
}


+ (NSData *)createBodyWithBoundary:(NSString *)boundary
                        parameters:(NSDictionary *)parameters
                             paths:(NSArray *)images
                         fieldName:(NSString *)fieldName {

    NSMutableData *httpBody = [NSMutableData data];

    // add params (all params are strings)

    [parameters enumerateKeysAndObjectsUsingBlock:^(NSString *parameterKey, NSString *parameterValue, BOOL *stop) {

        [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", parameterKey] dataUsingEncoding:NSUTF8StringEncoding]];
        [httpBody appendData:[[NSString stringWithFormat:@"%@\r\n", parameterValue] dataUsingEncoding:NSUTF8StringEncoding]];
    }];

    // add image data

    for (UIImage *image in images) {

        NSString *filename  = @"Profile_img";
        NSData *data      = UIImageJPEGRepresentation(image, 0.5);

        NSString *mimetype  = @"image/jpeg";

        NSLog(@"->%@->%@", filename, mimetype);

        [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fieldName, filename] dataUsingEncoding:NSUTF8StringEncoding]];
        [httpBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", mimetype] dataUsingEncoding:NSUTF8StringEncoding]];
        [httpBody appendData:data];
        [httpBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }

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

    return httpBody;
}

+ (NSString *)generateBoundaryString {

    return [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];
}

希望它有所帮助!

您可以有更多想法here

答案 1 :(得分:0)

UIImage *imageobj=[UIImage imageNamed:@"a.jpg"];
NSData *data1=UIImagePNGRepresentation(imageobj);
NSString *encodedString = [data1 base64Encoding];
       NSString * strEncondingdata=[NSString stringWithFormat:@"%@%@",@"data:image/png;base64,",encodedString];
  NSLog(@"%@",strEncondingdata);

您需要将图像转换为此格式,然后才能发送到服务器。还有一个是检查图像分辨率,如果图像是更高分辨率的服务器端没有上传那么,前端你需要压缩图像。 使用下面的代码压缩图像。

 NSData *unscaledData = UIImagePNGRepresentation(imageobj);

if (unscaledData.length > 5000.0f ) {


    UIImage *image2 = [self imageWithImage:image scaledToSize:CGSizeMake(image.size.width/2, image.size.height/2)];
    NSData  *finalData = UIImagePNGRepresentation(image2);


    if (finalData.length > 5000.0f ) {

        image3 = [self imageWithImage:image2 scaledToSize:CGSizeMake(image2.size.width/2, image2.size.height/2)];

    }
}


-(UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
   {
// Create a bitmap context.
UIGraphicsBeginImageContextWithOptions(newSize, YES, [UIScreen mainScreen].scale);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;

 }