-1

//webteam code for upload image

var hoardingjson = { _id: id, populationincomegroup: incomeGroupArray, availablebydate: availDate, title: title, description: desc, onemonthprice: oneMprice, threemonthsprice: threeMprice, sixmonthsprice: sixMprice, oneyearprice: oneYrprice, locality: locality, streetname: streetName, trafficdensity: trafficDensity, populationcategory: populationDensity, ownername: ownerName, mobile: mobile, leaseowner: currenrOwnerName, length: hoardingWidth, breadth: hoardingHeight, latitude: lat, longitude: lon, registereddate: currentTimestamp, createdate: "", updatedate: "", status: "", ownerid: ownerid };

var form_data = new FormData();
var imageCount = document.getElementById("editImages").files.length;
for (i = 0; i < imageCount; i++) {
    form_data.append("file", document.getElementById("editImages").files[0]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", server_url + "UpdateHoarding", true);
xhr.setRequestHeader("hoardingjson", JSON.stringify(hoardingjson));
xhr.send(form_data);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            success = true;
            $("#updateHoardingModal").modal("hide");
            alert("Hoarding is updated successfully");
            location.href = "home.jsp";
        }
    }
}

Ios code:

NSString * jsosSt=[self strOfthedata];

UIImage *imageOne = [UIImage imageNamed:@"edit.png"];
NSData *imageData1 = UIImageJPEGRepresentation(imageOne,0.6f);
NSString *fileName1 = [NSString stringWithFormat:@"%ld%c%c.jpeg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];

NSDictionary *params=@{@"token":appdeligate.userInf.tokenId,@"hoardingjson":[self strOfthedata]};

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"URL/CreateHoarding" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    [formData appendPartWithFileURL:[NSURL fileURLWithPath:savedImagePath] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];



} error:nil];


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableString *strParams = [[NSMutableString alloc]init];
for (NSString *key in [params allKeys]) {
    [strParams appendFormat:@"%@=%@", key, params[key]];
    [strParams appendString:@"&"];
}

[strParams deleteCharactersInRange:NSMakeRange([strParams length]-1, 1)];
[request setHTTPBody:[strParams dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];




NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.
                  // You are responsible for dispatching to the main queue for UI updates
                  dispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      [progressView setProgress:uploadProgress.fractionCompleted];
                      NSLog(@"%f",uploadProgress.fractionCompleted);
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];

[uploadTask resume];
Abbut John
  • 133
  • 2
  • 9
  • Have you look at this [question](http://stackoverflow.com/questions/37941306/download-one-file-at-a-time-using-afnetworking/) it is asked for download you need to implement same just for upload – Nirav D Jul 15 '16 at 11:16
  • are you using AFNetwork , correct – Anbu.Karthik Jul 15 '16 at 11:18
  • Yes Afnetworking 3 but the image form part is not receiving , but json is getting delivered while i am sending [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; even json is getting what i need to check for receiving images correctly to server – Abbut John Jul 19 '16 at 11:15

2 Answers2

0

------------This is working for me---------------

-(void)UploadImagewithUrl:(NSString *)serviceURL 
                 withJson:(NSString *)jsonStr 
                withtoken:(NSString *)Token_id 
           withImageArray:(NSArray *)imageURlArray 
                 callback:(SuccessCallback)callback 
           failerCallback:(FailureCallback)failercallback {

NSString *baserl=[NSString stringWithFormat:@"%@?token=%@&hoardingjson=%@",serviceURL,Token_id,jsonStr];
baserl = [baserl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lineEnd = @"\r\n";
NSString* twoHyphens = @"--";
NSString* boundary = @"*****";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:baserl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    for (int i=0; i<imageURlArray.count; i++) {

        NSData *imageData = [[NSFileManager defaultManager] contentsAtPath:[imageURlArray objectAtIndex:i]];
        NSString *fileName = [NSString stringWithFormat:@"%ld%c.jpeg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a'];


        [formData appendPartWithFormData:[twoHyphens dataUsingEncoding:NSUTF8StringEncoding] name:@"twoHyphens"];
        [formData appendPartWithFormData:[boundary dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"boundary"];
        [formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"lineEnd"];
        [formData appendPartWithFileData:imageData
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"image/jpeg"];
    }

    [formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding] name:@"lineEnd"];
    [formData appendPartWithFormData:[twoHyphens dataUsingEncoding:NSUTF8StringEncoding] name:@"twoHyphens"];
    [formData appendPartWithFormData:[boundary dataUsingEncoding:NSUTF8StringEncoding]
                                name:@"boundary"];
    [formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding]
                                name:@"lineEnd"];


} error:nil];


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request


              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.


                  [SVProgressHUD showProgress:uploadProgress.fractionCompleted status:@"Uploading"];

                  if (uploadProgress.fractionCompleted==1)
                  {
                      [SVProgressHUD dismiss];
                  }

                  // You are responsible for dispatching to the main queue for UI updates
                  dispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      [progressView setProgress:uploadProgress.fractionCompleted];


                   NSLog(@"---response---- %@",uploadProgress);

                  });


              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {


                  if (error) {
                      failercallback([NSString stringWithFormat:@"%ld",error.code],@"failer");
                       NSLog(@"Error: %@", error);

                  } else {

                        callback(YES,responseObject);
                       NSLog(@"%@ %@", response, responseObject);
                }
              }];

[uploadTask resume];
}
tomi44g
  • 3,266
  • 1
  • 20
  • 28
Abbut John
  • 133
  • 2
  • 9
0

Here it is using AFNetworking

   AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
    //do not put image inside parameters dictionary as I did, but append it!
    [formData appendPartWithFileData:nsdataFromBase64String name:@"" fileName:@"" mimeType:@"image/jpeg"];

}
success:^(NSURLSessionDataTask *task, id responseObject)
 {
     //here is place for code executed in success case
 }
failure:^(NSURLSessionDataTask *task, NSError *error)
{
     //here is place for code executed in error case
 }];
  1. stringURL is the URL where you want to upload/send the image.
  2. NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:pBytes options:0]; Where nsdataFromBase64String is image conversion to base64 string and decode the same on server
    1. Check the mime type if you want png.
gurmandeep
  • 1,227
  • 1
  • 14
  • 30