-(IBAction)uploadToServer :(id)sender
{
NSString *str1=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"intro.mp4"];
NSLog(#"str1=%#",str1);
NSString *escapedUrlString = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"escapedUrlString=%#",escapedUrlString);
NSURL *videoURL = [NSURL URLWithString:escapedUrlString];
NSLog(#"videoURL=%#",videoURL);
NSData *newdata = [NSData dataWithContentsOfFile:escapedUrlString];
webdata=[NSData dataWithData:newdata];
NSLog(#"webData = %#",webdata);
[self post:webdata];
}
- (void)post:(NSData *)fileData
{
NSData *videoData = fileData;
NSString *urlString = #"http://rompio.com/web_service/web.php?method=upload_video&user_id=4";
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:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\".mp4\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[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(#"returnString=== %#", returnString);
}
It's easy to do with the AFNetworking library and you can also use it to track the progress of the video upload. You can download AFNetworking library from here.
And for configuring AFnetworking please refer this Link.
And this code will used to send the video on server
NSString *videoURL = [[NSBundle mainBundle] pathForResource:#"myVideo" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath: videoURL]];
AFHTTPClient *httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://www.example.com"]];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/videoupload.php" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:videoData name:#"file" fileName:#"myVideo.mov" mimeType:#"video/quicktime"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest: request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite)
{
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(#"Video Uploaded Successfully");}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {NSLog(#"Error : %#", operation.responseString);}];
[operation start];
Store selected video URL in some variable :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
selectedVideoURL = info[UIImagePickerControllerMediaURL];
}
}
For latest version of AFNetworking, below code is used.
NSMutableDictionary *dictParams1 = [[NSMutableDictionary alloc]init];
[dictParams1 setObject:userID forKey:"userID"];
[dictParams1 setObject:otherparam forKey: "otherparam_Key"];
NSLog(#"REQUEST URL : ------------------ %#", API_URL);
NSLog(#"PARAMETERS : ------------------ %#", dictParams1);
NSString *strFileName = [NSString stringWithFormat:#"%ld.mov", [[NSDate date] timeIntervalSince1970]];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:APIAddFeedVideo parameters:dictParams1 constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:selectedVideoURL name:#"videofile" fileName:strFileName mimeType:#"video/mov" error:nil]; // video/quicktime //video/mp4
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
//[progressView setProgress:uploadProgress.fractionCompleted];
});
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"VIDEO UPLOAD RESPONSE : %# %#", response, responseObject);
}
}];
[uploadTask resume];
Related
I'm Trying to upload image to server with headers Hope my code is fine but i don't know it cannot upload. My code is
{
NSDictionary *headers = #{ #"content-type":#"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
#"p-auth-token":self.token};
NSString *urlString = [ NSString stringWithFormat:#"http://ica.com/facilitator/server/v1/media"];
UIImage *image= profile_Image;
NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:#"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"file\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setAllHTTPHeaderFields:headers];
[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 stringWithString:string] 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];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *statusDict = [[NSDictionary alloc]init];
statusDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[SVProgressHUD dismiss];
NSLog(#"Images form server %#", statusDict);
}] resume];
}
Try AFNetworking with below code,
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"upload_url" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data name:#"upload_file_name" fileName:#"somefilename.jpg" mimeType:#"mime_type_of_file"] // you file to upload
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
I desperately need to show a progress bar or an activity indicator , because image uploading takes time. Below is my code, I cannot figure it out why progress bar is not showing. I have used ProgressHUD.
[ProgressHUD show:#"Please wait..."];
NSDictionary *params =#{ #"name":self->Name.text, #"contact_no":self->ContactNo.text,#"email_id":self->EmailId.text,#"s_date":Date,#"s_time":Time,#"streat":Street,#"city":City,#"state":State};
NSData *uploadData = Data;
NSString *urlString = [NSString stringWithFormat:#"http://fsttest.com/iosservice/supremo/add_supremo"];
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"];
NSString *kNewLine = #"\r\n";
NSMutableData *body = [NSMutableData data];
for (NSString *name in params.allKeys) {
NSData *values = [[NSString stringWithFormat:#"%#", params[name]] dataUsingEncoding:NSUTF8StringEncoding];
[body appendData:[[NSString stringWithFormat:#"--%#%#", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"", name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#%#", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:values];
[body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file_name\"; filename=\"test\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:uploadData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
choice 1
as your way continution add the delegate and check like
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
NSLog(#"progress/total %f",progress/total);
}
choice 2
modify your request from sendSynchronousRequest to sendAsynchronousRequest for e,g
// NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
call the method like
// set URL
[request setURL:[NSURL URLWithString:baseUrl]];
// add your progress bar here
[ProgressHUD show:#"Please wait..."];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
[ProgressHUD dismiss];
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
if ([data length] > 0 && error == nil)
[delegate receivedData:data];
// hide the progress bar here
}
}];
You can use AFNetworking for easily upload image. here click on AFNeworking Download. Same as your code upload images.
-(void)imageUpload
{
#try
{
[self progressViewDispaly];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setTimeoutInterval:600.0];
[manager POST:YOUR_WEB_SERVICE_NAME parameters:YOUR_REQUEST_PARA constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
for(NSString *strImageName in ImageArray) //if multiple images use image upload
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:strImageName];
if (path != nil)
{
NSData *imageData = [NSData dataWithContentsOfFile:path];
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"job_files[]"] fileName:[NSString stringWithFormat:#"%#",[[strImageName componentsSeparatedByString:#"/"] lastObject]] mimeType:#"image/jpeg"];
}
else
{
}
}
} progress:^(NSProgress * _Nonnull uploadProgress)
{
[self performSelectorInBackground:#selector(makeAnimation:) withObject:[NSString stringWithFormat:#"%f",uploadProgress.fractionCompleted]];
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
[SVProgressHUD dismiss];
[_progressView removeFromSuperview];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
} #catch (NSException *exception)
{
NSLog(#"%#",exception.description);
}
}
-(void)makeAnimation:(NSString *)str
{
float uploadProgress = [str floatValue];
[_progressView setProgress:uploadProgress];
}
-(void)progressViewDispaly
{
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:#"statusBarWindow"] valueForKey:#"statusBar"];
_progressView = [[UIProgressView alloc] init];//WithProgressViewStyle:UIProgressViewStyleBar];
_progressView.frame = CGRectMake(0, 0, CGRectGetWidth(statusBar.frame),20);
_progressView.backgroundColor = [UIColor blueColor];
_progressView.progressTintColor = [UIColor whiteColor];
[statusBar addSubview:_progressView];
}
I am trying to send a post request.
Here is my try:
-(void)Test{
NSDictionary * orderMasterDict = #{#"distributorId":#10000,
#"fieldUsersId": #3,
#"itemId":#0,#"orderMatserId":#56358 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:jsonString2 forKey:#"orderMaster"];
[_params setObject:jsonString forKey:#"orderDetails"];
[_params setObject:[NSString stringWithFormat:#"3"] forKey:#"userId"];
[_params setObject:[NSString stringWithFormat:#"ALRAISLABS"] forKey:#"subsCode"];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"imageUpload";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http://192.168.0.102:8080/Demo/Test/create"];
// 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=%#", BoundaryConstant];
[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(_uploadImageView.image, 0.6);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"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", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error){
NSLog(#"ERROR :",error);
}else{
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"response status code: %ld", (long)[httpResponse statusCode]);
if ([httpResponse statusCode] == 200) {
NSLog(#"StatusCode : %ld",(long)[httpResponse statusCode]);
}else{
NSLog(#"Error");
}
}
}] resume];}
How to make a multipartFormData request?
I tried googling for it, couldn't find any answer suitable for this situation, and thought well .Please help me finding the right solution.
Thanks in advance.
First you change your image in NSData then help of AFNetworking you can post your image.
NSData *data = UIImagePNGRepresentation(yourImage);
imageData = [data base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
Then use this code:
NSMutableDictionary *finaldictionary = [[NSMutableDictionary alloc] init];
[finaldictionary setObject:imageData forKey:#"image"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST: [NSString stringWithFormat: #"%#%#", IQAPIClientBaseURL, kIQAPIImageUpload] parameters: finaldictionary constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) { }
progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Success response=%#", responseObject);
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingAllowFragments error: nil];
NSLog(#"%#", responseDict);
}
failure: ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Errorrrrrrr=%#", error.localizedDescription);
}
];
By using Alamofire
-(void)CreateOrder{
NSString * urlString = [NSString stringWithFormat:#"YOUR URL"
NSDictionary * orderMasterDict = #{#"distributorId":stakeholderID,
#"fieldUsersId": userID,
#"itemId":#0,#"orderMatserId":#0 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSDictionary * consumerDetails = #{#"consumerName":Globals.PatientName,#"consumerReferenceId":Globals.PatientID,#"notes":Globals.PatientNotes,#"cunsumerContacNumber":#"456464654654"};
NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
//retrieving userId from UserDefaults
prefs = [NSUserDefaults standardUserDefaults];
NSString * userIdString = [prefs stringForKey:#"userID"];
NSDictionary *parameters = #{#"orderMaster": jsonString2, #"orderDetails" : jsonString ,#"userId" : userIdString,#"subsCode" : #"ABC_MDENT"};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//For adding Multiple images From selected Images array
int i = 0;
for(UIImage *eachImage in selectedImages)
{
UIImage *image = [self scaleImage:eachImage toSize:CGSizeMake(480.0,480.0)];
NSData *imageData = UIImageJPEGRepresentation(image,0.3);
[formData appendPartWithFileData:imageData name:#"imageUpload" fileName:[NSString stringWithFormat:#"file%d.jpg",i ] mimeType:#"image/jpeg"];
i++;
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(#"responseObject : %#",responseObject);
if (error) {
NSlog(#"error")
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == 200) {
resposeStatusCode = [responseObject objectForKey:#"statusCode"];
}else{
NSLog(#"requestError");
}
}
}];
[uploadTask resume]; }
I know this question has been asked earlier as well but my issue is a bit different.
I want to upload an image to the PHP server and i want to send more parameters along with an image from an iOS.
I searched on the google and found two solutions:
Either we will send an image as Base64 encoded string in JSON. Referred link.
Or we will upload an image to server using form data. I have referred this link. If someone refers me this way, then please help me to add more parameters in this API.
Now my question is, which one is the best way to upload an image to the server and i have to send more parameters (username, password and more details) in the same web service call.
Thanks in advance.
You can upload image from iOS App to PHP server like this two way:
Using New AFNetworking :
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
NSString *stringUrl =#"http://www.myserverurl.com/file/uloaddetails.php?"
NSString *string =#"http://myimageurkstrn.com/img/myimage.png"
NSURL *filePath = [NSURL fileURLWithPath:string];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:userid,#"id",String_FullName,#"fname",String_Email,#"emailid",String_City,#"city",String_Country,#"country",String_City,#"state",String_TextView,#"bio", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:stringUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileURL:filePath name:#"userfile" error:nil];//here userfile is a paramiter for your image
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#",[responseObject valueForKey:#"Root"]);
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:#"myappname" message:string delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:#"myappname" message:[error localizedDescription] delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];
}];
Second use NSURLConnection:
-(void)uploadImage
{
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *urlString = [ NSString stringWithFormat:#"http://yourUploadImageURl.php?intid=%#",1];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------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 stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\r\n", 1]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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];
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
This both way working fine for uploading image from app to php server hope this helps for you.
Using AFNetworking this is how I do it:
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setObject:#"myUserName" forKey:#"username"];
[params setObject:#"1234" forKey:#"password"];
[[AFHTTPRequestOperationLogger sharedLogger] startLogging];
NSData *imageData;
NSString *urlStr = [NSString stringWithFormat:#"http://www.url.com"];
NSURL *url = [NSURL URLWithString:urlStr];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
imageData = UIImageJPEGRepresentation(mediaFile, 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:imageData name:#"mediaFile" fileName:#"picture.png" mimeType:#"image/png"];
}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"File was uploaded" message:#""
delegate:self cancelButtonTitle:#"Close" otherButtonTitles: nil];
[alert show];
}
failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
{
NSLog(#"request: %#",request);
NSLog(#"Failed: %#",[error localizedDescription]);
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
{
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
Try with Restkit
Here is link Restkit image upload with parameter
You can get Restkit help from here Restkit integration step
Try this.
-(void)EchoesPagePhotosUpload
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
[self startIndicator];
});
//NSLog(#"%#",uploadPhotosArray);
NSMutableArray *uploadPhotosByteArray=[[NSMutableArray alloc] init];
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:0]];
NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
if(conversionImage.size.height>=250&&conversionImage.size.width>=250)
{
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self performSelectorInBackground: #selector(LoadForLoop) withObject: nil]; NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
for(int img_pos=0;img_pos<[uploadPhotosArray count];img_pos++)
{
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:img_pos]];
NSData *imageData = UIImageJPEGRepresentation(conversionImage,1.0);
[Base64 initialize];
NSString *uploadPhotoEncodedString = [Base64 encode:imageData];
//NSLog(#"Byte Array %d : %#",img_pos,uploadPhotoEncodedString);
[uploadPhotosByteArray addObject:uploadPhotoEncodedString];
}
dispatch_async(dispatch_get_main_queue(), ^{
NSString *photo_description=[webview stringByEvaluatingJavaScriptFromString: #"document.getElementById('UploadPicsDesc').value"];
NSString *uploadPhotoImageName=#"uploadPhoto.jpg";
NSDictionary *UploadpicsJsonResponseDic=[WebserviceViewcontroller EchoesUploadPhotos:profileUserId imageName:uploadPhotoImageName Image:uploadPhotosByteArray PhotoDescription:photo_description];
//NSLog(#"%#",UploadpicsJsonResponseDic);
NSString *UploadPhotosStatusString=[UploadpicsJsonResponseDic valueForKey:#"Status"];
NSLog(#"UploadPhotosStatusString :%#",UploadPhotosStatusString);
NSString *uploadPhotosCallbackstring=[NSString stringWithFormat:#"RefreshForm()"];
[webview stringByEvaluatingJavaScriptFromString:uploadPhotosCallbackstring];
});
});
}
else {
UIAlertView *ErrorAlert=[[UIAlertView alloc] initWithTitle:#"Error" message:#"Please Upload Photo Above 250x250 size" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[ErrorAlert show];
NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
}
}
-(void)uploadImage
{
NSString *mimetype = #"image/jpeg";
NSString *myimgname = _txt_fname.text; //#"img"; //upload image with this name in server PHP FILE MANAGER
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *imageDataa = UIImagePNGRepresentation(chooseImg.image);
NSDictionary *parameters =#{#"fileimg":defaults }; //#{#"uid": [uidstr valueForKey:#"id"]};
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
//here post url and imagedataa is data conversion of image and fileimg is the upload image with that name in the php code
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:#"http://posturl/newimageupload.php"
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageDataa
name:#"fileimg"
fileName:myimgname
mimeType:mimetype];
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
[uploadImgBtn setTitle:#"Uploaded" forState:UIControlStateNormal];
[chooseImg setImage:[UIImage imageNamed:#"invoice-icon.png"]];
if([[responseObject objectForKey:#"status"] rangeOfString:#"Success"].location != NSNotFound)
{
[self alertMsg:#"Alert" :#"Upload sucess"];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#", error.description);
[chooseImg setImage:[UIImage imageNamed:#"invoice-icon.png"]];
uploadImgBtn.enabled = YES;
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
float myprog = (float)totalBytesWritten/totalBytesExpectedToWrite*100;
NSLog(#"Wrote %f ", myprog);
}];
// 5. Begin!
[operation start];
}
Try this this is work for me.
NSData *postData = [Imagedata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:apiString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDictft = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
I am trying to upload an image from my app to my server. I am following this tutorial (http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/). When I copy the code from the tutorial I get a bunch of warnings and errors, so I have modified it as below.
The uploadImage method is being called, and twitterImage contains the right photo, but the image is not being uploaded into the user_photos directory. Any recommendations would be great!
Here is my app code:
-(void)uploadImage {
NSData *imageData = UIImageJPEGRepresentation(twitterImage, 90);
NSString *urlString = #"http://website.com/user_photo_upload.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------673864587263478628734";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data;
boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"rn--%#rn",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-streamrnrn"
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"rn--%#--rn",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding];
}
Here is my user_photo_upload.php file:
<?php
$uploaddir = '../user_photos/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://website.com/user_photos/{$file}";
}
?>
In my suggestion, you can use ASIHTTPRequest framework for image uploading to the server. You can download the framework from here. It is simple easily understandable.
See the below code regarding image uploading using ASIHTTPRequest
NSData *imgData = UIImageJPEGRepresentation(IMAGE, 0.9);
formReq = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
formReq.delegate = self;
[formReq setPostValue:VAL1 forKey:KEY1];
if (imgData) {
[formReq setData:imgData withFileName:[NSString stringWithFormat:#"ipodfile.jpg"] andContentType:#"image/jpeg" forKey:#"userfile"];
}
[formReq startSynchronous];
You can also refer a nice tutorial here
If you want to move from NSMutableURLRequest then best bet is AFNetworking get it from here
ASIHTTPRequest is not being maintained and should not be used as said by developer of library here
Example oF image upload
-(void)call
{
//the image name is Denise.jpg i have uses image you can youse any file
//just convert it to nsdat in an appropriateway
UIImage *image= [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Denise" ofType:#"jpg"]];
// getting data from image
NSData *photoData= UIImagePNGRepresentation(image);
// making AFHttpClient
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"your url string"]];
//setting headers
[client setDefaultHeader:#"multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY" value:#"Content-Type"];
[client setDefaultHeader:#"key" value:#"value"];
NSMutableURLRequest *request1 = [client multipartFormRequestWithMethod:#"POST" path:#"application/uploadfile" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//setting body
[formData appendPartWithFormData:[[NSString stringWithFormat:#"Value"] dataUsingEncoding:NSUTF8StringEncoding] name:#"Key"];
[formData appendPartWithFormData:[[NSString stringWithFormat:#"Value"] dataUsingEncoding:NSUTF8StringEncoding] name:#"Key"];
//...
[formData appendPartWithFileData:photoData name:#"file_data" fileName:#"file.png" mimeType:#"image/png"];
}];
[request1 setTimeoutInterval:180];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
// use this float value to set progress bar.
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(#"%#",responseObject);
NSLog(#"response headers: %#", [[operation response] allHeaderFields]);
NSLog(#"response: %#",jsons);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if([operation.response statusCode] == 403)
{
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [error debugDescription]);
}];
[operation start];
}
When You are appending the image to body the Content-Disposition should be an attachment not form-data, just before you are appending the image-data on the body. so replace the following code:
[body appendData:[#"Content-Disposition: form-data;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
with this:
[body appendData:[#"Content-Disposition: attachment;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];