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
{
}
}
Related
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 am trying to upload image with some text data. But When i try it for image upload only. it works! But for param, I am getting result=null. so data is sending null. here is my code.
-(void)uploadImage : (UIImage *)image : (NSString *)url : (NSString *)param
{
NSLog(#"URL : %#", url);
NSLog(#"param : %#", param);
NSData *myData=UIImagePNGRepresentation(image);
NSMutableURLRequest *request;
NSString *urlString = url;
NSString *filename = #"image";
request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSDictionary *temp = #{#"result" : #"rob"
};
//opening boundary
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:#"--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#.png\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:myData]];
//params
[postbody appendData:[ [temp description] dataUsingEncoding:NSUTF8StringEncoding]];
//closing boundary
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
// conn.delegate = self;
[conn start];
}
may any expert help me what i am missing?
You could use a library like AFNetworking for all your requests. It's very easy and makes your code more readable. Here is a way to create a multipart file upload with parameters (https://github.com/AFNetworking/AFNetworking#creating-an-upload-task-for-a-multi-part-request-with-progress)
NSDictionary *params = #{
#"result" : #"rob"
}
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:#"file://path/to/image.jpg"] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
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
I am trying to migrate to NSURLSession so I can send multiple images to my server and stop when I get the needed response. But my completion block never gets called. Would appreciate if you could tell me if I am doing the migration correctly.
Here is my old code that works fine-
-(void) sendImgWithText:(UIImage*)img
{
NSURL *requestURL = [NSURL URLWithString:#"Some URL"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"*****";
NSString *lineEnd = #"\r\n";
NSString *twoHyphens = #"--";
// 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)
// UIImage *imgColor = [UIImage imageNamed:#"9.jpg"];
UIImage * imageToPost = [[UIImage alloc] init];
UIImageWriteToSavedPhotosAlbum(imageToPost, nil, nil, nil);
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"%#%#%#", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"%#%#%#%#", twoHyphens,boundary, twoHyphens,lineEnd] 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"];
NSLog(#"%#",requestURL);
NSLog(#"%f,%f",imageToPost.size.height,imageToPost.size.height);
// set URL
[request setURL:requestURL];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
And here is the version(I got most of it from other stack overflow articles)
- (void) serverRequestWithImage:(UIImage *)img completion:(void (^)(id responseObject, NSError *error))completion
{
NSURL *requestURL = [NSURL URLWithString:#"Some URL"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"*****";
NSString *lineEnd = #"\r\n";
NSString *twoHyphens = #"--";
// 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];
UIImage * imageToPost = [[UIImage alloc] init];
imageToPost = img;
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"%#%#%#", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"%#%#%#%#", twoHyphens,boundary, twoHyphens,lineEnd] 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"];
NSLog(#"%#",requestURL);
NSLog(#"%f,%f",imageToPost.size.height,imageToPost.size.height);
// set URL
[request setURL:requestURL];
NSURLSessionTask *task =
[session
dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// report any network-related errors
NSLog(#"Got Response 1");
if (!data) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
});
}
return;
}
// report any errors parsing the JSON
NSError *parseError = nil;
_responseData = [NSMutableData dataWithData:data];
if (_responseData) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, parseError);
});
}
return;
}
// if everything is ok, then just return the JSON object
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(_returnedData, nil);
});
}
}];
[task resume];
}
And here is my call method from the other class
- (IBAction)GetData:(id)sender
{
[_imageView setImage:[UIImage imageNamed:#"9.jpg"]];
msg = [[Message alloc] init];
[msg initData];
msg.delegate=self;
[msg serverRequestWithImage:_imageView.image completion:^(id responseObject, NSError *error)
{
if (responseObject) {
// do what you want with the response object here
NSLog(#"Got Data");
} else {
NSLog(#"%s: serverRequest error: %#", __FUNCTION__, error);
}
}];
}
Items:
I didn't see the initialization of NSURLSession. That's something you should show in your question. You could also check in your "send image" method that session is non-nil.
It looks like you are starting with a file (#"9.jpg"). If so, -[NSURLSession uploadTaskWithRequest:fromFile:completionHandler:] might save you a bunch of trouble.
Unrequested advice, with all that entails: :)
In my view, -serverRequestWithImage:completion: is a poor name for that method. It implies that it returns a request object, and does not tell you that it actually sends the request. Something active, like -uploadImage:completionHandler: might be better.
Idiomatically, all method names should start lowercase, i.e. -getData:.
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);