How to save the image in my server - objective-c

i am uploading the Image,which is taken from the camera or gallery.
i am successfully getting the image and when i uploading it i am getting error in simulator User_file=(null).
My Updating code is
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
NSData *dataItems=UIImageJPEGRepresentation(image, 0.1);
NSString *convertimage=[[NSString alloc]initWithData:dataItems encoding:NSUTF8StringEncoding];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:#"http:my url"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
//
// NSString *boundary = #"---------------------------14737809831466499882746641449";
// NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
// [urlRequest 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=\"user_file\"; filename=\"%d\"\r\n", 1]] dataUsingEncoding:NSUTF8StringEncoding]];
//
// [body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//
// [body appendData:[NSData dataWithData:dataItems]];
//
// [body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//
// [urlRequest setHTTPBody:body];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *UserID = [prefs stringForKey:#"sfffehr_id"];
NSLog(#"%#",UserID);
NSString *params=[[NSString alloc]initWithFormat:#"sfffehr_id =%# & user_file=%#",UserID,convertimage];
NSLog(#"%#",params);
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[dataTask resume];
my response is
fdg[1816:949041] user_file=(null)
fdg[1816:949041] Logo Changed
fdg[1816:949041] Response:<NSHTTPURLResponse: 0x136a2bcb0> { URL: url } { status code: 200, headers {
fdg[1816:949041] Data = {"response":"yes","success":"User profile picture updated successfully"}
When i check in my server i did't find my saved image.
How to save the image in my server, please help me .
I tried many methods but it can't help me.
Thank you.

I have made some corrections on your code. Try this now:
UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
NSData *dataItems=UIImageJPEGRepresentation(image, 0.1);
NSString *convertimage = [[NSString alloc] initWithData:dataItems encoding:NSUTF8StringEncoding];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:#"http://469.5350.747.4557/~lcall/index.php/webservices/update_profile_picture"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[urlRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *UserID = [prefs stringForKey:#"user_id"];
//Populate a dictionary with all the regular values you would like to send.
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:UserID forKey:#"user_id"];
[parameters setValue:convertimage forKey:#"user_file"];
// add params (all params are strings)
for (NSString *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_file\"; filename=\"image.png\"\r\n"]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:dataItems]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:body];
// getting an NSString
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil){
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[dataTask resume];
Note:
I have make necessary corrections in your code & Its Error free. But i have not tested it. Please check.
I hope it will work for you.

Related

How can i upload text and image data in a single request to server Objective c

I am using this dictionary but not able to upload.
dictionary = #{
kRequest: sign_in_owner,
o_first_name: s_fname,
o_middle_name: s_mname,
o_last_name: s_lname,
o_email_id: s_email,
o_primary_no: s_pnum,
o_alternative_no: s_anum,
o_project: s_proj,
o_block: s_block,
o_flat: s_flat,
o_total_sq_ft: s_square,
o_flat_intercom_no: s_intercom,
o_maintenance: s_maintenance};
Here is my rest of the code:
NSMutableArray* s_photo=[dictAttributes objectForKey:kPhoto];
isPhoto=NO;
// 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 = #"photo[]";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http://-----"];
// 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 dictionary) {
[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", param] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
if (s_photo) {
[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:[s_photo objectAtIndex:0]];
[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];
You can use AFNetworking Framework
It provides methods to upload text and image at a time (in one service call).
NSData *imageData = UIImageJPEGRepresentation(imgAttachment, 0.5);
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://yourURL" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (imageData != nil) {
[formData appendPartWithFileData:imageData name:#"param_name" fileName:#"AnyNameForImage.jpg" mimeType:#"image/jpeg"];
}
} 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
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"ERROR : %#", error.description);
} else {
NSLog(#"Response Headers : %#", response);
NSLog(#"Response Data : %#", responseObject);
}
}];
[uploadTask resume];

- connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite: never call

I want to notify my user about the progress of the upload of some Mpeg 3 files. Just one.
but I get issue as I say in the title.
My upload code is here
- (NSString *) upload: (NSData*) postData {
NSString *str;
NSURL *url = [NSURL URLWithString:#"http://example.com/test.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
request.HTTPMethod = #"POST";
NSString *boundary = #"unique-consistent-string";
// 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)
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add mp3 data
if (postData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=audio\r\n", #"audioFormKey"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: audio/mpeg3\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:postData];
[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 *postLength2 = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength2 forHTTPHeaderField:#"Content-Length"];
NSLog(postLength2);
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if(data.length > 0)
{
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(str);
}
}];
return str;
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
NSLog(#"bytes transfer %li" ,(long)bytesWritten);
}
Here the Log "bytes transfer" is never call.
Thanks a lot for support
A bit odd to be calling sendAsynchronousRequest: and then sendSynchronousRequest: in the completion handler?
In any case, you aren't configuring the URL connection to have a delegate and, thus, your delegate method is never called.
You'll need to allocated and instantiate the URLConnection and then configure it to use your object as the delegate. And it needs to conform to the NSURLConnectionDelegate protocol.

Upload A File Into A Server - Objective C/Xcode/Mediawiki

I want to upload a UIImage into a server. For this I am using the following lines of code ::
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
imageView.image = image;
NSData *pngData = UIImagePNGRepresentation(imageView.image);
NSString *imageFile = #"image.png";
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [docDir stringByAppendingPathComponent:imageFile];
NSString *dataIS=[NSString base64StringFromData:pngData length:[pngData length]];
[pngData writeToFile:filePath atomically:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[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:#"Content-Disposition: form-data; name=\"image\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:pngData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
But, I am getting the following error in gdb ::
Your request could not be processed. Request could not be handled.
I am also confused over the proper use of urlString i.e. I am doubtful over my correct use of it.
If I however use the following urlString, I am able to upload my image file into the server ::
NSString *urlString = [NSString stringWithFormat:#"http://xxxx.com/mediawiki/api.php?action=upload&filename=image.png&url=%#&token=%#", url, token] ;
With reference to the API for mediawiki (http://www.mediawiki.org/wiki/API:Upload), can someone help me to sort it out ?? Thanks and Regards.
I have same problem to upload multiple images and data but i am use AFNetworking class and Upload multiple images into server.
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"your URL"]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
path = [[NSString alloc] initWithString:[URL absoluteString]];
vdict = #{
// Your Parameter Pass
};
[self checkmultiple:vdict];
-(void)checkmultiple:(NSDictionary*)vdict
{
AFHTTPRequestOperation *op = [manager POST:path parameters:vdict constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
for(i = 0;i<[appDelegate.gblarrydata count];i++)
{
NSString *paths = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"New Folder"];
// NSLog(#"%#",paths);
NSString *documentsDirectory = paths;
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[[appDelegate.gblarrydata objectAtIndex:i]valueForKey:#"nameimage"]];
NSData *data1 =[[NSData alloc]initWithContentsOfFile:getImagePath];
NSString *data2 =[[appDelegate.gblarrydata objectAtIndex:i] valueForKey:#"Note"];
[formData appendPartWithFileData:data1 name:[NSString stringWithFormat:#"pimage%d",i+1] fileName:[NSString stringWithFormat:#"pimage%d.jpg",i+1] mimeType:#"image/jpeg"];
if(![data2 isEqualToString:#""])
{
[formData appendPartWithFormData:[data2 dataUsingEncoding:NSUTF8StringEncoding]
name:[NSString stringWithFormat:#"pnotes%d",i+1]];
}
}
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Upload success");
NSString *returnString = [NSString stringWithFormat:#"%#",[responseObject JSONRepresentation]];
NSLog(#"Reg Date:%#",returnString);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error:%#",error);
}];
[op start];
}
I had the same problem. I used ASIHTTPRequest, for uploading files, it works fine.
Uploading:
Imagefile:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Ben" forKey:#"names"];
[request addPostValue:#"George" forKey:#"names"];
[request addFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photos"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
With Other data simultaneously:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// Upload a file on disk
[request setFile:#"/Users/ben/Desktop/ben.jpg" withFileName:#"myphoto.jpg" andContentType:#"image/jpeg"
forKey:#"photo"];
// Upload an NSData instance
[request setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
for Downloading to desired Path:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:#"/Users/ben/Desktop/my_file.txt"];
If you want to send image to server,send by data in encoded form,server can handle encoded form of image and they will get image data in encoded from.
// UIImage * img = [UIImage imageNamed:#"min.png"];
// NSData *imageData = UIImageJPEGRepresentation(img,0.2);
NSString *strUrl =[NSString stringWithFormat:#"%#/upload_file.php", [globalApp sharedUser].vg_dominio ];
//strUrl = #"http://192.168.1.100/mismedicinas/upload_file.php";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
request.HTTPMethod = #"POST";
request.timeoutInterval = 60;
request.HTTPShouldHandleCookies = false;
//[request setHTTPMethod:#"POST"];
NSString *boundary = #"----------SwIfTeRhTtPrEqUeStBoUnDaRy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
//[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableData *tempData = [NSMutableData data];
[tempData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[tempData appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"iphoneimage.xml\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[tempData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[tempData appendData:[NSData dataWithData:imageData]]; ///IMAGEN
[tempData appendData:[NSData dataWithData:cData]];
[tempData appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData: tempData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue: [NSString stringWithFormat:#"%d", body.length ] forHTTPHeaderField:#"Content-Length"];
request.HTTPBody =body;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"finalizacion %#", returnString);

iOS YouTube Video Upload Error

I am trying to upload a video using Objective-C and YouTube API but it is not working and return error at last step. The error reads "User authentication required".
I am following this API document specifically the one which is without metadata. I got the authentication token with ClientLogin API
I checked authentication token with NSLog and it's there. I see the upload API also returns Upload URL but when I send HTTP PUT request to retrieved Upload URL, it returns an error mentioned above.
Here's Upload Code
- (bool) upload:(NSString *)file {
NSData *fileData = [NSData dataWithContentsOfFile:file];
NSURL *url = [NSURL URLWithString:self.UploadURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"PUT"];
[request setValue:#"Content-Type" forHTTPHeaderField:#"application/octet-stream"];
[request setValue:#"Content-Length" forHTTPHeaderField:[NSString stringWithFormat:#"%ud", [fileData length]]];
[request setHTTPBody:fileData];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
if (response == nil) {
return NO;
} else {
return YES;
}
}
I also tried the Direct Upload method but this always gives me Invalid Request error. Below is the code.
- (bool) directUpload:(NSString *)file {
NSString *title = [file lastPathComponent];
NSString *desc = #"This is test video.";
NSString *category = #"People";
NSString *keywords = #"video";
NSString *boundary = #"--qwerty";
NSString *xml = [NSString stringWithFormat:
#"<?xml version=\"1.0\"?>"
#"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
#"<media:group>"
#"<media:title type=\"plain\">%#</media:title>"
#"<media:description type=\"plain\">%#</media:description>"
#"<media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%#</media:category>"
#"<media:keywords>%#</media:keywords>"
#"</media:group>"
#"</entry>", title, desc, category, keywords];
NSData *fileData = [NSData dataWithContentsOfFile:file];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"%#\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Type: application/atom+xml; charset=UTF-8\n\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Type: video/mp4\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Transfer-Encoding: binary\n\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:fileData];
[postBody appendData:[[NSString stringWithFormat:#"%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=\"%#\"", self.AuthToken] forHTTPHeaderField:#"Authorization"];
[request setValue:#"2" forHTTPHeaderField:#"GData-Version"];
[request setValue:[NSString stringWithFormat:#"key=%#", self.DeveloperKey] forHTTPHeaderField:#"X-GData-Key"];
[request setValue:[file lastPathComponent] forHTTPHeaderField:#"Slug"];
[request setValue:[NSString stringWithFormat:#"multipart/related; boundary=\"%#\"", boundary] forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%ud", [postBody length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"close" forHTTPHeaderField:#"Connection"];
[request setHTTPBody:postBody];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
if (response == nil) {
return NO;
} else {
return YES;
}
}
i think you should check this :-
https://developers.google.com/youtube/2.0/developers_guide_protocol_video_feeds
and you also check this :-
http://urinieto.com/2010/10/upload-videos-to-youtube-with-iphone-custom-app/

NSImage from NSPasteBoard to base64 for HTTP POST not working as expected

I'm playing around with trying to create a little menu item app to learn Cocoa/OS X programming.
Basically it's something that sits in your dock, you drag an image file to it, and it will upload the file to imgur and tell you the URL it was uploaded to.
It "works" in that imgur's API doesn't throw any errors back at me, but the images don't render properly either.
Applicable code:
ScreenshotController.m
- (void)uploadImage:(NSImage *)image
{
NSData *imageData = [image TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
imageData = [imageRep representationUsingType:NSPNGFileType properties:nil];
NSString *base64 = [imageData encodeBase64WithNewlines: NO];
NSString *jsonRequest = #"key=92428d1a5839df89cb8e87e8a31cd935&image=";
jsonRequest = [jsonRequest stringByAppendingString:[base64 stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSLog(#"Request: %#", jsonRequest);
NSData *requestData = [NSData dataWithBytes: [jsonRequest UTF8String] length: [jsonRequest length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://api.imgur.com/2/upload"]];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: requestData];
NSData *returnData = [ NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Returned Json: %#", returnString);
}
StatusItemView.m
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray *dragTypes = [NSArray arrayWithObjects:NSURLPboardType, NSFileContentsPboardType, NSFilenamesPboardType, nil];
[self registerForDraggedTypes:dragTypes];
}
return self;
}
//perform the drag and log the files that are dropped
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
NSPasteboard *pb = [sender draggingPasteboard];
if([[pb pasteboardItems] count] != 1){
return NO;
}
if([NSBitmapImageRep canInitWithPasteboard:pb]){
NSImage *image = [[NSImage alloc] initWithPasteboard:pb];
[[[ScreenshotController alloc] autorelease] uploadImage:image];
return YES;
}
return NO;
}
Here is an example image it uploaded to imgur, so you can see what I mean: http://imgur.com/6pLgG (the source file was a perfectly normal PNG).
Complete source code is here if you need to see anything else: https://github.com/zbuc/imgur
So I figured out a way to upload to the anon api, I hope this helps out.
- (void)uploadImageToImgur{
NSData *_imageData = UIImageJPEGRepresentation(image,90);
NSString *urlString = #"http://api.imgur.com/2/upload.json";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// file
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"image\"; filename=\".tiff\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:_imageData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// text parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//Set API key
[body appendData:[#"API_STRING_HERE" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSArray *decodedResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *imgurUrlString = [[[decodedResponse valueForKey:#"upload"] valueForKey:#"links"] valueForKey:#"imgur_page"];
[self uploadToImgurCompleteWithUrlString:imgurUrlString];
}];
}