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];
Related
I have made some image views and their button under them. When user select image from gallery it displays on image view. Now I want that image to be sent to server through PHP web service and use POST method. I want it to first convert it to base64 bits.
My code is
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"ddMMyyyyHHmmss"];
NSData *data = UIImageJPEGRepresentation(_img1.image, 1.0);
UIImage *imagedata = [UIImage imageWithData:data];
NSString * base64String = [data base64EncodedStringWithOptions:0];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
//---------- Compress photo----------
double compressionRatio = 1;
int resizeAttempts = 5;
while ([data length] > 1000 && resizeAttempts > 0)
{
resizeAttempts -= 1;
compressionRatio = compressionRatio*0.6;
data = UIImageJPEGRepresentation(imagedata,compressionRatio);
}
NSString *baseurl = #"myurl";
NSURL *dataURL = [NSURL URLWithString:baseurl];
NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:500.0];
[dataRqst setHTTPMethod:#"POST"];
NSString *stringBoundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
NSString *headerBoundary = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[dataRqst addValue:headerBoundary forHTTPHeaderField:#"Content-Type"];
NSMutableData *postBody = [NSMutableData data];
// -------------------- ---- image Upload Status -----------------------
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\"; filename=\"%#\"\r\n",[NSString stringWithFormat:#"%#.jpeg",theDate]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:data];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"--%#--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[dataRqst setHTTPBody:postBody];
self.conn = [[NSURLConnection alloc] initWithRequest:dataRqst delegate:self];
//SubmitDetailsViewController *presales = [self.storyboard instantiateViewControllerWithIdentifier:#"SubmitDetailsViewController"];
// [self.navigationController pushViewController:presales animated:YES];
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self->recieveData = [[NSMutableData alloc] init];
}
//------------- Response from server -------------
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[ self->recieveData appendData:data];
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
}
You can use AFNetworking library to do this. Add AFNetworking to your projec and import AFNetworking.h in to your class and you can then do something like,
UIImageView *imageView; // your image view
NSData *imgData = UIImageJPEGRepresentation(imageView.image, 1.0);
NSString *base64ImageStr = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSString *strToSend = [base64ImageStr stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSDictionary *parameters = #{#"yourServerKeyOrParameterForImage" : strToSend}; // you can add other parameters as well
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[[manager POST:#"your url" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"your response : %#",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error : %#",error.localizedDescription);
}]resume];
While capturing image from phone camera and uploading to server, app get crashed and getting this error:
[/BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreUI/CoreUI-371.4/Bom/Storage/BOMStorage.c:522] <memory> is not a BOMStorage file
2016-02-19 10:31:53.413 Appname[520:141128] Received memory warning.
Message from debugger: Terminated due to memory issue.
Code:
UIImage *finalImage, *rotatedImage;
finalImage = self.capturedimg;
if (finalImage.imageOrientation == UIImageOrientationRight)
{
rotatedImage = [self imageRotatedByDegrees:finalImage deg:90];
}else if (finalImage.imageOrientation == UIImageOrientationDown)
{
rotatedImage = [self imageRotatedByDegrees:finalImage deg:180];
}else if (finalImage.imageOrientation == UIImageOrientationLeft)
{
rotatedImage = [self imageRotatedByDegrees:finalImage deg:-90];
}else if (finalImage.imageOrientation == UIImageOrientationUp)
{
rotatedImage = [self imageRotatedByDegrees:finalImage deg:360];
}
imageView.image = rotatedImage;
-(void)sendImage:(id)sender{
CGFloat compression = 0.5f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;
imageData = UIImageJPEGRepresentation(imageView.image, compression);
while ([imageData length] > maxFileSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(imageView.image, compression);
}
NSString *dateString = [self.serviceConnector datenow];
NSString *urlString = [NSString stringWithFormat:#"%#",SinglechatImageUpload_Url];
[allObjectArray removeAllObjects];
NSDictionary *tempDict = [NSDictionary dictionaryWithObjectsAndKeys:
// Object and key pairs
dateString, #"imageuploaddate",
self.CaptionTxtfield.text, #"imagecaption",
nil];
[allObjectArray addObject:tempDict];
[self chatimgUrlString:urlString postValue:allObjectArray imageData:imageData];
}
- (void)chatimgUrlString:(NSString*)urlStr postValue:(NSMutableArray*)array imageData:(NSData*)imgData{
NSString *jsonString;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array
options:NSJSONWritingPrettyPrinted
error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",urlStr]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10];
[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:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//json sting parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"jsonstring\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
receivedData = nil;
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
receivedData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
receivedData = nil;
connection = nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
#try {
//send the data to the delegate
id jsonObjects = [NSJSONSerialization JSONObjectWithData:reciveddata options:NSJSONReadingMutableContainers error:nil];
NSLog(#"json : %#",jsonObjects);
}
#catch (NSException *exception) {
NSLog(#"Exception error didfinishload: %#",exception.reason);
receivedData = [[NSMutableData alloc]init];
[self.delegate requestReturnedData:receivedData];
}
}
Try to add Autoreleasepool block in your while loop:
while ([imageData length] > maxFileSize && compression > maxCompression)
{
#autoreleasepool {
compression -= 0.1;
imageData = UIImageJPEGRepresentation(imageView.image, compression);
}
}
Hi i am very beginner in Ios and in my project i need to send "Username" and "Password" and "UserImage" to server using NSURLConnection and for this i have inserted this three fields(username,password,userimage) in one Dictionary and i am posting this dictionary to server but using my below code details are not sending to server please help me what did i do here wrong
my code:-
#interface SendingImagesToServer ()
{
NSMutableData *body;
}
#end
#implementation SendingImagesToServer
- (void)viewDidLoad {
[super viewDidLoad];
NSData *imageData;
UIImage * image;
NSError *error = nil;
image = [UIImage imageNamed:#"friendship.jpg"];
imageData = UIImageJPEGRepresentation(image, 0.1f);
NSDictionary *mainDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"James" ,#"username",
#"1234",#"Password",
imageData,#"image",
nil];
NSString *jsonString = [mainDict JSONRepresentation];
NSData * webbody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
body = [webbody mutableCopy];
NSString *urlstr = [NSString stringWithFormat:#"My url here"];
NSURL *url = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"imagename\"; filename=\"picture.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
if(imageData == nil && error!=nil) {
NSLog(#"nil");
}
else
{
NSLog(#"not nill");
}
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Successfully sending to server");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"error is %#",[error localizedDescription]);
}
#end
You create the request, but don't start it anywhere in your code. Also you don't create the NSURLConnection anywhere (at least not in the posted part).
The easiest way to achieve this would be to simply add this line at the end of your viewDidLoad method :
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
You can read more here
I want to upload an image on a server. I encode to 64-bit then I post. I am using this code:
NSURL *url=[[NSURL alloc] initWithString:#"http://boomagift.ramansingla.com/userpicture.php?email=sonal#gmail.com"];
NSMutableURLRequest *req=[[NSMutableURLRequest alloc] initWithURL:url];
[req setHTTPMethod:#"POST"];
// [req setValue:#"multipart/form-data; boundary=*****" forHTTPHeaderField:#"Content-Type"];
NSMutableData *postBody=[NSMutableData data];
NSString *boundary=#"*****";
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSString *this=[pickedImageData base64EncodedString];
[postBody appendData: [this dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:postBody];
NSHTTPURLResponse *response=nil;
NSError *error=[[NSError alloc] init];
NSData *responseData;
responseData=[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
NSLog(#"%#",responseData);
if(responseData&&[responseData length])
{
NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(#"%#",dictionary);
}
else
{
NSLog(#"hello");
}
-(NSArray *)getResizedUImage:(UIImage *)getImage otherValueOne:(float)newWidth otherValueSecond:(float)newHeight
{
CGRect rect = CGRectMake(0.0, 0.0, newWidth, newHeight);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 1);
[getImage drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSArray *loadImageDateArray = [[NSArray alloc]init];
UIImage *imageConvert = img;
NSData *data = UIImageJPEGRepresentation(imageConvert, 0.8);
NSString *base64String = [data base64EncodedStringWithOptions:0];
loadImageDateArray = [NSArray arrayWithObject:base64String];
return loadImageDateArray;
}
This code part return base 64 try this
I update my answer use this function, this function return base 64
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);