24 Jun 2017

Posting image to server using multipart file...


Posting image to server using multipart file...

we can use this method to post any type of file using multipart/*  ....


Add delegates in  .h  <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

- (IBAction)profilePicChangeBtnAction:(id)sender {
    

    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.delegate = self;
    [self presentViewController:imagePickerController animated:YES completion:nil];

}

// This method is called when an image has been chosen from the library or taken from the camera.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //You can retrieve the actual UIImage
    profileImage = [info valueForKey:UIImagePickerControllerOriginalImage];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.profilePicImageView.image = profileImage;
    });
    
    //Or you can get the image url from AssetsLibrary
    //    NSURL *path1 = [info valueForKey:UIImagePickerControllerReferenceURL];
    
//    NSData *compressedImageData=[self testData:profileImage];
//    DLog(@"compressedImageData ====>> %lu KB",compressedImageData.length/1024);
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"upload-image.png"];
    NSData *imageData1 = UIImagePNGRepresentation(profileImage);
    //you can also use UIImageJPEGRepresentation(img 1); for jpegs
    [imageData1 writeToFile:path atomically:YES];
    
    NSString *boundary = [self generateBoundaryString];
    
    // configure the request
    NSMutableURLRequest *request;
    if (previously uploaded image id == nil ) {

    request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@""]];

    }else {

        NSString * urlString =  [NSString stringWithFormat:@"",previously uploaded image id];
        request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    }
    [request setHTTPMethod:@"POST"];
    
    NSUserDefaults *authToken= [NSUserDefaults standardUserDefaults];
    NSString *authStr=[authToken valueForKey:@"authToken"];
    [request addValue:authStr forHTTPHeaderField:@"X-Authorization"];
    
    // 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:@{} paths:@[path] fieldName:@"file"]; // provide path & field name as required.
    
    request.HTTPBody = httpBody;
    
    NSURLSession *session = [NSURLSession sharedSession];
   
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"error = %@", error);
            return;
        }
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        
        NSLog(@"result =====> %@", result);
    }];
    [task resume];  
}


- (NSData *)createBodyWithBoundary:(NSString *)boundary
                        parameters:(NSDictionary *)parameters
                             paths:(NSArray *)paths
                         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 (NSString *path in paths) {
        NSString *filename  = [path lastPathComponent];
        NSData   *data      = [NSData dataWithContentsOfFile:path];
        NSString *mimetype  = [self mimeTypeForPath:path];
        
        [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 *)mimeTypeForPath:(NSString *)path {
    // get a mime type for an extension using MobileCoreServices.framework
    
    CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
    assert(UTI != NULL);
    
    NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
    assert(mimetype != NULL);
    
    CFRelease(UTI);
    
    DLog(@"mimetype +++++++>>>> %@",mimetype);
    return mimetype;
}

- (NSString *)generateBoundaryString {
    return [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];

}

No comments:

Post a Comment

Recent Posts

Codable demo

Link: https://www.dropbox.com/s/kw7c1kgv1628bh7/codableDemo.zip?dl=0