0

I am Using This Code

NSString *strrrr=@"";
UIImage *chooseImage=[infoDict valueForKey:@"filename"];

if (chooseImage)
{
    strrrr=@"filename.JPG";
}                                                                       

urlString=[NSString stringWithFormat:@"%@KabuterCompanyService?companyID=%@&companyTypeID=%@&serviceTypeID=%@&description=%@&serviceCreatedBy=%@&startDate=%@&endDate=%@&location=%@&promotionalText=%@&promotionalDocument=%@&colOfResponseOptionVO=%@&responseOptionQuestionVO=%@&componentName=%@&companyServiceID=%@&submit=%@&quickSend=%@&ajaxreq=%@&access_token=%@&commandResultAttributes : promotionalDocumentVO.mimeTypeVO.name,companyVO.companyName,serviceTypeVO.name,colOfOwnerEntitlementVO.entitlementID,colOfOwnerEntitlementVO.entitleableID,colOfSubscriberEntitlementVO.entitlementID,colOfSubscriberEntitlementVO.entitleableID,colOfResponseOptionVO.sequenceNumber,colOfResponseOptionVO.attributeValue,colOfResponseOptionVO.url,colOfResponseOptionVO.expiresOn,responseOptionQuestionVO.attributeValue,*",BaseURL2,[infoDict valueForKey:@"vendorID"],@"893688751",@"-2114174907",[infoDict valueForKey:@"EventName"],[infoDict valueForKey:@"HostName"],[infoDict valueForKey:@"StartDate"],[infoDict valueForKey:@"EndDate"],[infoDict valueForKey:@"Location"],[infoDict valueForKey:@"EventDescription"],strrrr,[infoDict valueForKey:@"colOfRequestParameterVO"],[infoDict valueForKey:@"responseOptionQuestionVO"],@"KabuterCompanyService",@"null",@"Create",@"true",@"json",[[NSUserDefaults standardUserDefaults] objectForKey:@"tokenID"]];

urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

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

NSData *imageData = UIImageJPEGRepresentation(chooseImage, 1.0);

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

NSString *boundary = @"WebKitFormBoundaryjrFKfnmMBcXRMamI";

// 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=%@; name=filename.JPG\r\n", @"name"] 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]];

// 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"];


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

Not upload my image in Server And when my android team doing same thing they are getting image in server using this Android plz help me

Please help if someone know about this thing why i am unable to get my image in server.

Arasuvel
  • 2,971
  • 1
  • 25
  • 40
vikas
  • 1
  • 1
  • 2

2 Answers2

0

your Request should be like :

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];

// how to send   parameters with request that you ma need when also uload  image //


       [_params setObject:promotionalDocument    forKey:[NSString stringWithFormat:@"promotionalDocument"]];
       [_params setObject:mobile   forKey:[NSString stringWithFormat:@"mobile"]];






        // the boundary random string, that will not repeat in post data

        NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";

        // your server paramter for image
        NSString* FileParamConstant = @"serverParamterForImage";

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

        // 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(image, 1.0);
        if (image) {
            [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];

// then you can use that request
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
  • i want to pass parameter *promotionalDocument :; filename="yoga-2017-may-21.png" Content-Type: image/png * how can i pass – vikas Aug 29 '17 at 07:45
  • @chek update promotionalDocument file name of image is send NSString* FileParamConstant = @"serverParamterForImage"; – Abdelahad Darwish Aug 29 '17 at 07:48
0

I am facing the same issue. But I didn't get solutions using NSMutableURLRequest. You can use AFNetworking or NSURLSessionUploadTask

NSURLSessionUploadTask:

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

NSURL *url = YOUR_SERVICE_URL;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

[request setHTTPMethod:@"PUT"];

UIImage *image = [UIImage imageNamed:@"imageName"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
    if (!error && httpResp.statusCode == 200) {

        // Uploaded

    } else {

       NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode);
      }
}];

AFNetworking:

 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager POST:YOUR_SERVICE_URL parameters:YOUR_PARAMETER_DICTIONARY constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
             [formData appendPartWithFormData:IMAGE_DATA name:YOUR_KEY_NAME];

     } progress:^(NSProgress * _Nonnull uploadProgress)
     {
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"%@",responseObject);

     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
     }];
Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56