0

This my code from this link

Uploading Image via POST in Objective C

// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation(_chosenImage, 1.0f);
NSLog(@"%@", dataImage);
NSString *tempURLString = [APIStr stringByReplacingOccurrencesOfString:@"***" withString:@"upload"];

// set your URL Where to Upload Image
NSString *urlString = @"My URL String";

// set your Image Name
NSString *filename = @"My File Name";

// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
NSLog(@"%@", request);
[request setHTTPMethod:@"POST"];    
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"my_upload_file_name\"; filename=\"%@_.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@", postbody);
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];

// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"Response  %@",responseString);

This code not working for me.. I'm getting failed message. Is any wrong in my code.

And i tried this code also

https://jmsliu.com/3241/select-and-upload-multiple-photos-from-gallery-or-camera-in-ios.html

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

_chosenImage = info[UIImagePickerControllerEditedImage];
   [self uploadImageLegacy:_chosenImage];
}


- (void) uploadImageLegacy:(UIImage *)image {
NSString *tempURLString = [Str stringByReplacingOccurrencesOfString:@"***" withString:@"upload"];
//upload single image
NSURL *url = @"My URL here";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
[request setHTTPMethod:@"POST"];
NSString *POST_BODY_BOURDARY = @"SportuondoFormBoundary";
NSString *contentTypeValue = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", POST_BODY_BOURDARY];
[request addValue:contentTypeValue forHTTPHeaderField:@"Content-type"];

NSMutableData *dataForm = [NSMutableData alloc];
[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"param1\";\r\n\r\n%@", @"10001"] dataUsingEncoding:NSUTF8StringEncoding]];

NSData *imageData = UIImageJPEGRepresentation(image, 0.9);
[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"my_upload_file_name\"; filename=\"%@.jpg\"\r\n", @"test"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[NSData dataWithData:imageData]];

[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:dataForm];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
NSLog(@"Sent %lld, Total sent %lld, Not Sent %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
_receiveData = [NSMutableData data];
[_receiveData setLength:0];
completionHandler(NSURLSessionResponseAllow);
NSLog(@"NSURLSession Starts to Receive Data");
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
[_receiveData appendData:data];
NSLog(@"NSURLSession Receive Data");
}

 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"URL Session Complete: %@", task.response.description);

if(error != nil) {
    NSLog(@"Error %@",[error userInfo]);
} else {
    NSLog(@"Uploading is Succesfull");

    NSString *result = [[NSString alloc] initWithData:_receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", result);
}
}
Naresh
  • 16,698
  • 6
  • 112
  • 113

1 Answers1

1

I am using this code and working for me

    NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
    [_params setObject:[UserDict valueForKey:@"userid"] forKey:@"userid"];
    // YOU CAN ADD YOUR  PARAMETERS HERE


    NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
    NSString* FileParamConstant = @"file";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];

    NSMutableData *body = [NSMutableData data];

    //    NSData *bodyData = [appData createFormData:_params withBoundary:BoundaryConstant];
    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]];
    }
    // I AM RESIZING IMAGE YOU CAN SKIP
    UIImage *newSizeImage = [self imageWithImage:currentlyCapturedImage scaledToSize:newImageSize];

    NSData *imageData = UIImageJPEGRepresentation(newSizeImage, 1.0);

    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, timestamp] 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]];

now You have body with your parameters and image.

You can use this as body of request [request setHTTPBody:body];

and call the service

Hope it will helpful

EDIT

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

}];

[postDataTask resume];
Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
  • @iOS Make sure you change this `[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image%@.jpg\"\r\n",FileParamConstant, timestamp] dataUsingEncoding:NSUTF8StringEncoding]];` according to you – Prashant Tukadiya Feb 26 '18 at 07:10
  • What is _params userid – Naresh Feb 26 '18 at 07:11
  • @iOS it is example. you can put your parameter that need to pass in request with image – Prashant Tukadiya Feb 26 '18 at 07:13
  • @iOS are you sending any parameter to server along with image ? then use `_params` dictionary as per my example – Prashant Tukadiya Feb 26 '18 at 07:15
  • Yes I'm sending multiple parameters along with url – Naresh Feb 26 '18 at 07:15
  • @iOS for example if you are sending name parameter. then use like `[_params setObject:@"Prashant" forKey:@"name"];` – Prashant Tukadiya Feb 26 '18 at 07:17
  • ok, I understood thank you..., but can you please implement this with NSURLSession task. – Naresh Feb 26 '18 at 07:18
  • @ Prashant Tukadiya, Thank you very much to spent your valuable time for me... I tried but I'm getting the same message failed. So we check server side code after that I will try once again and I will inform you. – Naresh Feb 26 '18 at 07:35
  • @ Prashant Tukadiya, with out doing any changes in server side my image uploaded successfully...Thank you very much... – Naresh Feb 26 '18 at 07:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165806/discussion-between-ios-and-prashant-tukadiya). – Naresh Feb 26 '18 at 08:04