Uploading video through http - ios

So this is my attempt:
I first create an "Image picker" which allows me to take the video:
- (IBAction)takeVideo:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
self.movieURL = info[UIImagePickerControllerMediaURL];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)viewDidAppear:(BOOL)animated {
self.movieController = [[MPMoviePlayerController alloc] init];
self.movieController.controlStyle = MPMovieControlStyleNone;
[self.movieController setContentURL:self.movieURL];
[self.movieController.view setFrame:CGRectMake (15, 125, 292, 390)];
self.movieController.view.backgroundColor = [UIColor clearColor];
[self.view addSubview:self.movieController.view];
[self.movieController play];
NSString *myString = [self.movieURL absoluteString];
//THE DATA IS RETURNING 0 :
NSData *videoData = [NSData dataWithContentsOfFile:myString];
NSLog(#"%#",[NSByteCountFormatter stringFromByteCount:videoData.length countStyle:NSByteCountFormatterCountStyleFile]);
[self setImageDataToSend:videoData];
}
- (void)moviePlayBackDidFinish:(NSNotification *)notification {
[[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[self.movieController stop];
[self.movieController.view removeFromSuperview];
self.movieController = nil;
}
I am not receiving any data from the URL though?
I then try and upload it to my site:
-(IBAction)uploadvideotowebsite:(id)sender{
//you can use any string instead "com.mycompany.myqueue"
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mcompany.myqueue", 0);
//turn on
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
dispatch_async(backgroundQueue, ^{
PFUser *user = [PFUser currentUser];
NSString * url = [NSString stringWithFormat:#"http://******.co.uk/****/imageupload.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSMutableData *body = [[NSMutableData alloc]init];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *String = #"Content-Disposition: form-data; name=\"image\"; filename=\"";
NSString *String2 = #"video";
NSString *String3 = #".MOV\"\r\n";
NSString *connection1 = [String stringByAppendingString: String2];
NSString *done = [connection1 stringByAppendingString: String3];
[body appendData:[[NSString stringWithFormat:done] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: audio/basic\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:_imageDataToSend];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//Send the Request
NSData* returnData = [NSURLConnection sendSynchronousRequest: request
returningResponse: nil error: nil];
//serialize to JSON
if (!returnData){
return; // or handle no connection error here
}else{
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
//parsing JSON
bool success = [result[#"success"] boolValue];
if(success){
NSLog(#"Success=%#",result[#"msg"]);
//[self performSegueWithIdentifier:#"toshow" sender:self];
}else{
NSLog(#"Fail=%#",result[#"msg"]);
}
}
dispatch_async(dispatch_get_main_queue(), ^{
//turn off
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
});
});
}
I am receiving no errors. But I am receiving a file of size 0kb on my site.
Can anybody explain why I am getting no data from the video?

Can anybody explain why I am getting no data from the video?
Sure, here's your mistake:
NSString *myString = [self.movieURL absoluteString];
should be path
NSString *myString = [self.movieURL path];
NSData *videoData = [NSData dataWithContentsOfFile:myString];
NSLog(#"%#",[NSByteCountFormatter stringFromByteCount:videoData.length countStyle:NSByteCountFormatterCountStyleFile]);

Related

Facing issue while uploading a video to server. Requirement is upload binary formate and mp4 type files

I am facing an issue while uploading videos in binary formate and mp4 type files. I implemented below functionalities for uploading videos. But I got response status like 415 and 500 reports. Actually this is the first time I upload a mediatype file please give me any suggestions and other links.facing issue while uploading video in binary formate and mp4 type files.
-(void)camerabuttonHandlerqas{
UIAlertController * picker = [UIAlertController alertControllerWithTitle:#"Pick an image using" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { }];
UIAlertAction* takeVideo = [UIAlertAction actionWithTitle:#"TakeVideo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
imagePicker.view.tag = 100;
[self presentViewController:imagePicker animated:YES completion:nil]; }];
[picker addAction:picture];
[picker addAction:cancel];
picker.view.tintColor = [UIColor grayColor];
[self presentViewController:picker animated:YES completion:nil];
}
#pragma mark - <UIImagePickerControllerDelegate>
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
videoURL = info[UIImagePickerControllerMediaURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* videoPath = [NSString stringWithFormat:#"%#/test_%d.mp4", [paths objectAtIndex:0],arc4random_uniform(1000)];
NSURL *outputURL = [NSURL fileURLWithPath:videoPath];
[self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession)
{
switch (exportSession.status) {
case AVAssetExportSessionStatusFailed:
NSLog(#"status failed");
break;
case AVAssetExportSessionStatusCompleted:{
NSLog(#"status success %# ",videoPath);
NSMutableDictionary *data = [NSMutableDictionary new];
videoURL = info[UIImagePickerControllerMediaURL];
[data setObject:[self generatePostDataForData:[NSData dataWithContentsOfFile:videoPath]] forKey:#"SelectedvideoURL"];
imagePickerIsSelected = YES;
[self postData:data];
break;
}
}];
[picker dismissViewControllerAnimated:YES completion:nil]; }
- (NSData *)generatePostDataForData:(NSData *)uploadData
{ // Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\";
filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength: [postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
// Add the closing boundry:
[postData appendData: [#"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
-(void) postData:(NSData *)data
{
service = [NSString stringWithFormat:#"http://1.1.1.1:8080/testing/postapi/photoUpload/uploadVideo?videoName=video_%d&type=mp4",arc4random_uniform(1000)]
delegate = delegateInstance;
service = [service stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLFragmentAllowedCharacterSet]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:service]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
// set Content-Type in HTTP header
[request setValue:#"mp4/MOV" forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// add image data
if (videoData) {
[body appendData:videoData];
}
// setting the body of the post to the reqeust
[request setHTTPBody:videoData];
// set URL
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
} }]; [dataTask resume]; }

I want to send user id with image upload in ios

I want to Upload an image and in my code it is uploading correctly, But I want to send one user id along with the image in post, Please some one can explain.
I want to Upload an image and in my code it is uploading correctly, But I want to send one user id along with the image in post, Please some one can explain.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2;
self.profileImageView.clipsToBounds = YES;
dic= [[NSMutableDictionary alloc]init];
NSUserDefaults *defaults10 = [NSUserDefaults standardUserDefaults];
NSData *imageData = [defaults10 dataForKey:#"image"];
UIImage *contactImage = [UIImage imageWithData:imageData];
profileImageView.image = contactImage;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id1 = [defaults objectForKey:#"ID"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)Pictureupload:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init] ;
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
// profileImageView.image = image;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSDate *currentDate = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
NSString* cleanedString = [[localDateString stringByReplacingOccurrencesOfString:#"." withString:#""]stringByReplacingOccurrencesOfString:#":" withString:#""];
NSString *cleanedString2 = [cleanedString stringByAppendingFormat:#"%d",1];
NSString *finalUniqueImageNAme ;
finalUniqueImageNAme = [cleanedString2 stringByAppendingString:#".jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 90);
NSString *urlString = #"http://vygears.com/tcdc-portfolio/Abdul/chat/Pupload_file.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Successfully uploaded");
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
[self dismissModalViewControllerAnimated:true];
}
else
{
NSLog(#"Connection could not be made");
}
});
});
[picker dismissModalViewControllerAnimated:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
webdata =[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
// NSString *responseString = [[NSString alloc]initWithData:webdata encoding:NSUTF8StringEncoding];
dic=[NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSLog( #"Success %#",dic);
NSString * res = [dic objectForKey:#"url"];
NSURL *imageURL = [NSURL URLWithString:res];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
// Update the UI
self.profileImageView.image = [UIImage imageWithData:imageData];
NSUserDefaults *defaults10 = [NSUserDefaults standardUserDefaults];
[defaults10 setObject:imageData forKey:#"image"];
[defaults10 synchronize];
});
});
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
I have done like this now it is working fine.
// ----------------------------------Upload Image --------
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// ----------------------------------Passing user_id in Post--------
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:id1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Successfully uploaded");
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

upload picked image in objective-c

I'm new to objective-c. I need the image picked in the first function to be uploaded in the second one:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)uploadPic:(UIButton *)sender {
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:#"yourImage"], 1.0f);
//added after editing
// set your URL Where to Upload Image
NSString *urlString = #"http://url";
// set your Image Name
NSString *filename = #"uploaded_file";
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[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=\"userfile\"; filename=\"%#.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:#"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);
//end editing
}
The added code, in btween editing comments, is the one that I use to upload the image
You should use neither UIImageJPEGRepresentation nor UIImagePNGRepresentation. Those will lose the image's meta-data, make the file larger (or if you choose a JPEG compression factor to make the NSData smaller, it will degrade the image), etc.
I'd suggest that you save the UIImagePickerControllerReferenceURL and, then, when the user chooses to save the image, that you go back to the Photos framework and retrieve the underlying NSData of the image.
So, make sure to import the Photos framework:
#import Photos;
Also, define a property to capture the URL:
#property (nonatomic, strong) NSURL *imageReferenceURL;
And then capture this URL when you get the image:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
self.imageReferenceURL = info[UIImagePickerControllerReferenceURL];
[picker dismissViewControllerAnimated:YES completion:nil];
}
And when you go to upload the picture, retrieve the original asset's NSData from the Photos framework:
- (IBAction)uploadPic:(UIButton *)sender {
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[self.imageReferenceURL] options:nil];
PHAsset *asset = [result firstObject];
if (asset) {
PHImageManager *manager = [PHImageManager defaultManager];
[manager requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
// insert your code for uploading here, referencing the `imageData` here rather than `dataImage`.
// Or, I might recommend AFNetworking:
//
// For example, if your web service was expecting a `multipart/form-data` POST and was
// going to return a JSON response, you could do something like:
NSString *urlString = #"http://192.168.0.10/udazz/2.0/2.2/ios/1.0/actions.php?targ=user&subTarg=post&txtComment=123456&txtType=ff";
NSDictionary *parameters = #{#"targ" : #"user",
#"subTarg" : #"post",
#"txtComment" : #"123456",
#"txtType" : #"ff"};
NSURL *fileURL = info[#"PHImageFileURLKey"];
NSString *filename = [fileURL lastPathComponent];
NSString *mimeType = [self mimeTypeForPath:filename];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // if response is string rather than JSON, uncomment this line
[manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"userfile" fileName:filename mimeType:mimeType];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error = %#", error);
}];
}];
}
}
Or, if you want to use your own upload code, just adjust it to use NSURLSession (because NSURLConnection is now deprecated and you should never do synchronous network requests, anyway):
- (IBAction)uploadPic:(UIButton *)sender {
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[self.imageReferenceURL] options:nil];
PHAsset *asset = [result firstObject];
if (asset) {
PHImageManager *manager = [PHImageManager defaultManager];
[manager requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
// upload the `imageData`
NSURL *fileURL = info[#"PHImageFileURLKey"];
NSString *filename = [fileURL lastPathComponent];
NSString *mimeType = [self mimeTypeForPath:filename];
NSString *urlString = #"http://192.168.0.10/udazz/2.0/2.2/ios/1.0/actions.php?targ=user&subTarg=post&txtComment=123456&txtType=ff";
NSMutableURLRequest* request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[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=\"userfile\"; filename=\"%#\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", mimeType] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:imageData];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionTask *task = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:postbody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
}];
[task resume];
}];
}
}
By the way, my routine for programmatically determining the mime-type (because you really can't just assume the image is a JPEG; it could be a PNG, amongst other types, too) is as follows:
- (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);
return mimetype;
}
If you need to support iOS versions that predate the Photos framework, then use the ALAssetsLibrary to get the NSData. If you need example of how to do that (only if you need to support iOS versions before 8.0), let me know.
You are assigning the picked image to your imageView. So you can access it using the image property of that UIImageView.
You can access like:
- (IBAction)uploadPic:(UIButton *)sender
{
NSData *dataImage = UIImageJPEGRepresentation(self.imageView.image, 1.0f);
// Do your stuff here
}
I have done your requirement in my demo project. I have picked image using UIIMagePicker delegate function
#interface ViewController ()
{
UIImage *chooseImage;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSDate *time = [NSDate date];
NSDateFormatter* df = [NSDateFormatter new];
[df setDateFormat:#"ddMMyyyy-hhmmss"];
NSString *timeString = [df stringFromDate:time];
NSString *fileName = [NSString stringWithFormat:#"%#", timeString];
chooseImage = info[UIImagePickerControllerEditedImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectoryPath = [paths objectAtIndex:0];
NSLog(#"View Controller Path:%#",documentsDirectoryPath);
savedImagePath = [documentsDirectoryPath
stringByAppendingPathComponent:[NSString stringWithFormat: #"%#-%d.png", fileName, num]];
num += 1;
NSData *imageData = UIImagePNGRepresentation(chooseImage);
[imageData writeToFile:savedImagePath atomically:NO];
[picker dismissViewControllerAnimated:YES completion:NULL];
[self displayImage];
}
-(void)displayImage
{
self.imageView.image = chooseImage;
}
and from that method i have called another function->displayImage, which i am using for displaying image in UIImageView. Here below is code.

Upload image from Image Picker to Web server in Stream format

I need to upload the Image into the web server in stream format. Here i used Image Picker to select the images from the gallery.
// add image data
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[postData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", #"file"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:imageData];
[postData appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
- (IBAction)selectingPicture
{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
[picker release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ALERT_TITLE"
message:#"ALERT_MSG"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
#pragma mark -
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
imageData= UIImagePNGRepresentation(image); ////declare as a public variable in iterface
[picker dismissModalViewControllerAnimated:YES];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
-(void)WebserviceCallMtd
{
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Martin" forKey:#"names"];
[request addPostValue:#"Newyork" forKey:#"City"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
}
elow is my code , i am using in my project
- (void)uploadFile:(NSData*)imgData FileName:(NSString*)fileName Path:(NSString*)postPath{
isFileUploading = YES;
if (appDel.isOnline)
{
NSLog(#"file path = %#",postPath);
NSData *_lastImageData = [NSData dataWithData:imgData];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:postPath]];
[request setHTTPMethod:#"POST"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu",(unsigned long)[_lastImageData length]] forHTTPHeaderField:#"Content-Length"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ;
operation.inputStream = [NSInputStream inputStreamWithData:_lastImageData];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
if (totalBytesExpectedToWrite > 0) {
float progress = totalBytesWritten*100/totalBytesExpectedToWrite;
NSLog(#"%f",progress);
}
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Sent image: ");
[self.delegate uploadCompletedWithStatus:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed to send image");
NSLog(#"Error sending: Code:%li",(long)[error code]);
}];
[operation start];
}
else
{
}
}

Upload imagefile from iOS device with objective-c to an PHP

I want to upload an image from my iphone (from imagepicker) to my server (with an PHP-script). But how do I get the image from the imagepicker / ImageView to the script for upload?
Here is my database connection code:
NSString *brugernavn = [[NSUserDefaults standardUserDefaults] stringForKey:kBrugernavn];
NSString *maaltid = self.maaltid.text;
//NSString *rating = [segmentedControl titleForSegmentAtIndex:[segmentedControl selectedSegmentIndex]];
//NSString *rating = self.rating;
NSString *kommentar = self.kommentar.text;
NSString *place = self.place.text;
NSData *data = [NSData dataWithContentsOfFile:filepath];
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"brugernavn=%#&&maaltid=%#&&kommentar=%#&&place=%#&&thumbnail=%#&&submit",brugernavn,maaltid,kommentar,place,data];
[urlString appendFormat:#"%#", data];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *baseurl = #"http://example.com/upload.php";
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
And here is my code for the imagepicker:
// KAMERA - Aktiverer kameraet ved tryk på knap
- (IBAction)useCamera:(id)sender {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = #[(NSString *) kUTTypeImage];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
_newMedia = YES;
}
}
// KAMERA - Aktiverer kamerarullen ved tryk på knap
- (IBAction)useCameraRoll:(id)sender {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.SourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = #[(NSString *) kUTTypeImage];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
_newMedia = NO;
}
}
// KAMERA - Sender valgt billede til imageView
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = info[UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = info[UIImagePickerControllerOriginalImage];
_imageView.image = image;
if (_newMedia)
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image:finishedSavingWithError:contextInfo:), nil);
} else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
}
And here the imageView from my .h-file:
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
And here is the defination of my upload-field on PHP:
$_FILES['thumbnail']['name']
The user should take a picture og choose from the cameraroll and then write some info like title, description, etc. for the upload and then upload the image and info the server with the PHP-script.
Please help me :o)
It has been a while since I used this, but it worked then :)
NSData *imageData = UIImagePNGRepresentation(bilden);
NSString *filename = [NSString stringWithFormat:#"bild%d%#", bildnr,#".png"];
NSString *urlString = #"http://extranet.pool.se/stockholmsmassan/rita_pa_vaggen/sparabild.php";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
// second parameter information
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"epost\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[epost dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r \n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"return: %#",returnString);

Resources