i will create a new project that it save an image to a server
i don't know whats i do
i search in this site but i don't find a solutions
My apps now take a photo from the camera or from the iPhone albums but i won't to upload this photo to my server
this is my ViewController.m :
'
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Non è presente una Camera"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[myAlertView show];
}
}
- (void)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;
}
}
- (void)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;
}
}
- (IBAction)useUpload:(UIButton *)sender {
}
-(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])
{
}
}
-(void)image:(UIImage *)image
finishedSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
if (error) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Save failed"
message: #"Failed to save image"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Here's code from my app to post an image to our web server:
// 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=%#", boundary];
[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(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
Copied from here
This was first answer in Mr. Google reply
Related
here is my code I written for showing activityIndicator on the navigationBar.
In my project on every view, a loader is showing it is working fine either in the middle of the screen or else on network activityIndicator or loader on navigation.
But when I am trying to call below post method, activityIndicator is not showing (in this method only it is not working.)
I tried so many ways of writing programmatically and using storyboard.
Scenario 1 : Without entering reply content/message if click on submit button then activityIndicator will appear.
Scenario 2 : If I entered any reply content/message then activityIndicator will not show.
you can check this video: https://youtu.be/G_UZ_gLRlr8
#interface ViewController ()
{
UIActivityIndicatorView *activityIndicator;
}
#end
- (void)viewDidLoad {
[super viewDidLoad];
//adding activity indicator on the navigation bar
activityIndicator =
[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
activityIndicator.color=[UIColor blackColor];
UIBarButtonItem * barButton =
[[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
// Set to Left or Right
[[self navigationItem] setRightBarButtonItem:barButton];
}
- (IBAction)submitButtonClicked:(id)sender {
[activityIndicator startAnimating];
if([_messageTextView.text isEqualToString:#""] || [_messageTextView.text length]==0)
{
[utils showAlertWithMessage:#"Enter the reply content.It can not be empty." sendViewController:self];
}else
{
[self replyTicketMethodCall];
}
}
-(void)replyTicketMethodCall
{
if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
{
//connection unavailable
//[utils showAlertWithMessage:NO_INTERNET sendViewController:self];
[RKDropdownAlert title:APP_NAME message:NO_INTERNET backgroundColor:[UIColor hx_colorWithHexRGBAString:FAILURE_COLOR] textColor:[UIColor whiteColor]];
}else{
#try{
NSString *urlString=[NSString stringWithFormat:#"%#helpdesk/reply?token=%#",[userDefaults objectForKey:#"companyURL"],[userDefaults objectForKey:#"token"]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// attachment parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"media_attachment[]\"; filename=\"%#\"\r\n", file123] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", typeMime] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:attachNSData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// reply content parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"reply_content\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[_messageTextView.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSString * tickerId=[NSString stringWithFormat:#"%#",globalVariables.iD];
// ticket id parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"ticket_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[tickerId dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
NSLog(#"Request is : %#",request);
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"ReturnString : %#", returnString);
NSError *error=nil;
NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
if (error) {
return;
}
NSLog(#"Dictionary is : %#",jsonData);
// "message": "Successfully replied"
if ([jsonData objectForKey:#"message"]){
NSString * msg=[jsonData objectForKey:#"message"];
if([msg isEqualToString:#"Successfully replied"])
{
[RKDropdownAlert title:NSLocalizedString(#"success", nil) message:NSLocalizedString(#"Posted your reply.", nil)backgroundColor:[UIColor hx_colorWithHexRGBAString:SUCCESS_COLOR] textColor:[UIColor whiteColor]];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reload_data" object:self];
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
}
else if ([jsonData objectForKey:#"message"])
{
NSString *str=[jsonData objectForKey:#"message"];
if([str isEqualToString:#"Token expired"])
{
MyWebservices *web=[[MyWebservices alloc]init];
[web refreshToken];
[self replyTicketMethodCall];
}
}
else
{
[self->utils showAlertWithMessage:#"Something went wrong. Please try again." sendViewController:self];
}
NSLog(#"Thread-Ticket-Reply-closed");
}
}#catch (NSException *exception)
{
[utils showAlertWithMessage:exception.name sendViewController:self];
NSLog( #"Name: %#", exception.name);
NSLog( #"Reason: %#", exception.reason );
return;
}
#finally
{
NSLog( #" I am in replytTicket method in TicketDetail ViewController" );
}
}
}
So this is the problem I am facing.
What is going wrong? any solution for this?
use this method
[self performSelector:#selector(replyTicketMethodCall) withObject:self afterDelay:5.0];
instead of this
[self replyTicketMethodCall];
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];
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
{
}
}
Am trying to upload a videos to server. I have two choice to upload videos. First one is, Take video and upload it to server. Second one is, Choose video from photo library and upload it to server.
Step 1:
In this scenario, Take video and upload it to server is working good.
I got the response from server is "Return String: {"jsonstatus":"ok","message":"Thanks for your posting."}".
Now i try to get this video from server. In media_file it says "x.x.x.x/video/96b8954fbed797500da708fd7bad2261video.mov" - I played this video successfully.
Step 2:
But when i choose the video from photo library, it successfully choosed the video. Now i post this video to server.
I got the response from server is "Return String: {"jsonstatus":"ok","message":"Thanks for your posting."}".
Now i try to get this video from server. In media_file it says "Invalid File"
Am using to choose video is,
- (IBAction)act_UploadVideoBtn:(id)sender
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:YES completion:NULL];
}
And Delegate method is,
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// movieURL = [info valueForKey:UIImagePickerControllerMediaURL];
//
// [picker dismissViewControllerAnimated:YES completion:NULL];
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
NSString *moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
// NSLog(#"%#",moviePath);
movieURL=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)) {
UISaveVideoAtPathToSavedPhotosAlbum (moviePath, nil, nil, nil);
}
}
[picker dismissViewControllerAnimated:YES completion:NULL];
}
Give any ideas to solve this issue.
Could you describe your server side? So far I understand that this may be a full url problem. Maybe snippets of your json? Perhaps look over your permissions on the folder you are writing into. If you are using ubuntu and lamp as a stack (noob i know) make sure it is r+w, but not exec.
//push video path to NSData
NSData *webData = [NSData dataWithContentsOfURL:movieURL];
NSURL *url = [NSURL URLWithString:#"http://www.example.com/upload_media.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"+++++ABck";
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=\"YOURFILENAME\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: video/quicktime\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];//video/quicktime for .mov format
[body appendData:[NSData dataWithData:webData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",response);
NSLog(#"%#",error);
/*Server code*/
move_uploaded_file($_FILES["file"]["tmp_name"],$upload_dir['basedir'].'YOUR_DIR']);
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);