How to upload the image/photo to a server using AFNetworking? - ios

I am trying to upload the image/video to a webserver for iOS.
The uploading part of this server works fine. I checked it with Android version and I have already implemented the uploading method in Android app.
So I have found some codes for iOS on the stackoverflow.com
First, I am using the following code for uploading image.
But I can't upload at all and get the following result. I am using XCode6.1 on iOS8 SDK.
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x7fe24348d0b0 {NSUnderlyingError=0x7fe2434be120 "The request timed out.", NSErrorFailingURLStringKey=ServerURL, NSErrorFailingURLKey=ServerURL, NSLocalizedDescription=The request timed out.}
Here are the codes that I am using.
NSString* serverURL = #"http://www.myserver.com/file/postMedia.php";
UIImage *image = [UIImage imageNamed:#"sample.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSDictionary *param = #{#"userID":#"master",
[manager POST:serverURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"uploadedfile_thumb" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
....
});
return;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
....
});
Certainly, the server works fine.
I have definitely tested with Android code.
So I'd like to know the exact code for iOS.
Thank you

This is my working code uploading an image to the server using AFNetworking:
+ (void)uploadImage:(UIImage *)image
ForUser:(WECUser *)user
withSuccessBlock:(void (^)(NSDictionary *response))resultBlock
faliureBlock:(void (^)(NSError *error))faliureBlock {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyyMMddHHmmss";
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSString *fileName =
[NSString stringWithFormat:#"user_image_%#.jpg", dateString];
NSDictionary *dictionary = #{
#"user_id" : user._id,
#"resource_id" : user._id,
#"functioncode" : #"2000",
#"app_id" : [WECURLGenerator stringOfAppID],
#"file_name" : fileName
};
NSURLRequest *request = [[AFHTTPRequestSerializer serializer]
multipartFormRequestWithMethod:
#"POST" URLString:[WECURLGenerator stringOfImageUploadingBaseURL]
parameters:dictionary
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData
appendPartWithFileData:UIImageJPEGRepresentation(image, 0.6)
name:#"file1"
fileName:fileName
mimeType:#"jpg"];
} error:(NULL)];
AFHTTPRequestOperation *operation =
[[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,
id responseObject) {
NSDictionary *resultDict =
[NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingMutableLeaves
error:nil];
resultBlock(resultDict[#"record"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
faliureBlock(error);
}];
[operation start];
}
Hope this helps.

Your code looks fine, I am using same code for uploading an image using AFNetworking. But you haven't mentioned how you are picking the image. Because you can not upload an image directly like:
UIImage *image = [UIImage imageNamed:#"sample.png"];
Are you using UIImagepickerController for picking your image?
If YES than see my code;
-(IBAction)chooseImg:(id)sender{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
picker = [[UIImagePickerController alloc]init];
picker.allowsEditing = NO;
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
[self.navigationController presentViewController:picker animated:YES completion:nil];
}
else{
picker = [[UIImagePickerController alloc]init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.allowsEditing = YES;
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self.navigationController presentViewController:picker animated:YES completion:nil];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSURL *name = [info objectForKey:UIImagePickerControllerReferenceURL];
image = [info objectForKey:UIImagePickerControllerOriginalImage];
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *imageAsset){
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSDictionary *metadata = imageAsset.defaultRepresentation.metadata;
NSLog(#"Meta:%#",metadata);
NSString *str = [imageRep filename];
txtImg.text = str;
};
ALAssetsLibrary *assetLib = [[ALAssetsLibrary alloc]init];
[assetLib assetForURL:name resultBlock:resultBlock failureBlock:nil];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
NOTE: Here I used metadata to display name of the image,it's not necessary you can skip this.
Than in uploading part:
NSString* serverURL = #"http://www.myserver.com/file/postMedia.php";
//UIImage *image = [UIImage imageNamed:#"sample.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSDictionary *param = #{#"userID":#"master",
[manager POST:serverURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"uploadedfile_thumb" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
....
});
return;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
....
});
This works for me uploading an image.
Hope it works for you.

Related

objective-c,How to send file as a parameter

I want to upload my image from my phone gallery to the server so I am not able to upload my program ,it runs successfully and shows print -
NSLog(#">>>>>>>>>> enter in ");
but it could not upload image on the server ,when I checked it in the app then there is no image ,and I also checked parameter, I think I am not sending proper file format in the parameter.
Please can anyone help me with proper file formate how to convert it
`
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)img
editingInfo:(NSDictionary *)editingInfo
{
[picker dismissModalViewControllerAnimated:YES];
NSURL *imagePath = [editingInfo objectForKey:#"UIImagePickerControllerReferenceURL"];
imageName = [imagePath lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
localFilePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"localFilePath.%#",localFilePath);
}
- (IBAction)submitBtn:(id)sender
{
NSURL* url;
url = [NSURL URLWithString:UrlBasic];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
fileURL = [NSURL fileURLWithPath:localFilePath];
reqData=[[NSMutableDictionary alloc]initWithObjectsAndKeys:imageName1,#"image",#"addclassphotoactmobs",#"droot",schoolFolderA,#"schoolfolder",_choseGalleryTextF.text,#"gname",dividNum,#"classid",fileURL,#"uploadedfile",nil];
NSLog(#"reqData=%#",reqData);
[manager POST:UrlBasic parameters:reqData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { }
progress:nil
success:^(NSURLSessionTask *task, NSMutableDictionary *responseObject) {
NSLog(#" %#",responseObject);
NSLog(#">>>>>>>>>> enter in ");
[self.view makeToast:#"submitted ....."
duration:3.0
position:CSToastPositionCenter];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error-=%#",error);
// [self.view makeToast:#"Please check internet connection !"];
}];
}
[Updated with imageNameStr]
While uploading your image data, it is necessary to send Name of the file.To generate a file Name, Here I've used Date and time.
Add the Code below the Line NSLog(#"reqData=%#",reqData);
====================
You have missed the formData Code.
Where as the image is the actual image in the below code.
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyyMMddhhmmssSSS"];
NSString *imageNameStr = [NSString stringWithFormat:#"%#.jpg",[formatter stringFromDate:[NSDate date]]];
[sessionManager POST:appendURL
parameters:postParamDict
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if(image!=nil){
NSData * imageData = UIImageJPEGRepresentation(image,0.5f);
if(imageData!=nil){
[formData appendPartWithFileData:imageData
name:#"image"
fileName:imageNameStr
mimeType:#"image/jpg"];
}
}
}
progress:^(NSProgress * _Nonnull uploadProgress) {
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSLog(#"%#",responseObject);
if(success)
success (responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error %#",error);
if(failure)
failure (error);
}]

Error while uploading images taken from camera to server AFNetworking 3.0

I am using AFNetworking to send images to my server. When I pick images from Gallery every thing works fine. But when I pick image using Camera, the server sends me an error that its an invalid image.
Using UIImagePickerController to pick images from camera.
Code
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager.requestSerializer setValue:API_KEY_VALUE forHTTPHeaderField:API_KEY];
NSMutableURLRequest * request = [manager.requestSerializer multipartFormRequestWithMethod:#"POST" URLString:URL parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
UIImage *image = nil;
for (int i=0; i < [imagesArr count]; i++)
{
image = [imagesArr objectAtIndex:i];
// image = [UIImage imageNamed:[NSString stringWithFormat:#"%d", i+1]];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString * paramName = [NSString stringWithFormat:#"scrappygram_image[%d]",i];
[formData appendPartWithFileData:imageData name:paramName
fileName:[NSString stringWithFormat:#"image_%d",i]
mimeType:#"image/jpeg"];
}
} error:nil];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse response, id responseObject, NSError error)
{
if (error)
{
NSLog(#"Error: %#", error.localizedDescription);
[self.delegate apiFailedWithError:error andType:type];
} else
{
NSLog(#"%#", responseObject);
[self.delegate apiSuccessWithRespoonseDictionary:responseObject andType:type];
}
}] resume];
Did Finish Launching with options Code
[GMSPlacesClient provideAPIKey:GMSPLACES_API_KEY];
[GMSServices provideAPIKey: GMSPLACES_API_KEY];
[[IQKeyboardManager sharedManager] setEnable:YES];
[[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:true];
[self settingsForRemoteNotifications];
[[NSUserDefaults standardUserDefaults] setValue:DEBUG_API_FAILED_ERROR_SHOW_YES forKey:DEBUG_ERROR_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
return YES;
Use below method when uploading through camera.
- (void)selectPhotoFromCamera
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
//imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];
}

Same image saving to two separate fields?

I have 2 image views (imageView & imageTwo) and four buttons (takePhoto and selectPhoto for each image view). Tapping each button displays the taken or selected photo in the corresponding image view. Great.
HOWEVER, I'm attempting to save the two photos taken to my database. For some reason, the first photo taken saves to my two different database fields (the same photo appears in both fields, instead of each different photo saving to the two separate fields). That said, the data seems to save correctly (see XML output).
Why is this? See code below (sorry for the lengthy post).
viewcontroller.m
//PHOTO ONE UPLOAD TAKE AND SELECT
- (IBAction)selectPhoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
selectedImageView = self.imageView; // Add this
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)takePhoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
selectedImageView = self.imageView; // Add this
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)takePhotoTwo:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
selectedImageView = self.imageTwo; // Add this
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)selectPhotoTwo:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
selectedImageView = self.imageTwo; // Add this
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = info[UIImagePickerControllerEditedImage];
selectedImageView.image = image;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)saveButton:(id)sender {
//FIRST IMAGE DATA
NSData *imgData = UIImageJPEGRepresentation(self.imageView.image, 0.5);
NSMutableDictionary *file = [[NSMutableDictionary alloc] init];
NSString *base64Image = [imgData base64EncodedString];
[file setObject:base64Image forKey:#"file"];
NSString *timestamp = [NSString stringWithFormat:#"%d", (int)[[NSDate date] timeIntervalSince1970]];
NSString *imageTitle = _itemName.text;
NSString *filePath = [NSString stringWithFormat:#"%#%#.jpg",#"public://stored/", imageTitle];
NSString *fileName = [NSString stringWithFormat:#"%#.jpg", imageTitle];
[file setObject:filePath forKey:#"filepath"];
[file setObject:fileName forKey:#"filename"];
[file setObject:timestamp forKey:#"timestamp"];
NSString *fileSize = [NSString stringWithFormat:#"%lu", (unsigned long)[imgData length]];
[file setObject:fileSize forKey:#"filesize"];
//SECOND IMAGE DATA
NSData *secondimgData = UIImageJPEGRepresentation(self.imageTwo.image, 0.5);
NSMutableDictionary *secondfile = [[NSMutableDictionary alloc] init];
NSString *secondbase64Image = [secondimgData base64EncodedString];
[file setObject:secondbase64Image forKey:#"file"];
NSString *secondtimestamp = [NSString stringWithFormat:#"%d", (int)[[NSDate date] timeIntervalSince1970]];
NSString *secondimageTitle = secondtimestamp;
NSString *secondfilePath = [NSString stringWithFormat:#"%#%#.jpg",#"public://stored/", secondimageTitle];
NSString *secondfileName = [NSString stringWithFormat:#"%#.jpg", secondimageTitle];
[secondfile setObject:secondfilePath forKey:#"filepath"];
[secondfile setObject:secondfileName forKey:#"filename"];
[secondfile setObject:secondtimestamp forKey:#"timestamp"];
NSString *secondfileSize = [NSString stringWithFormat:#"%lu", (unsigned long)[secondimgData length]];
[secondfile setObject:secondfileSize forKey:#"filesize"];
[DIOSFile fileSave:file success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"File uploaded!");
//FIRST IMAGE FILE
[file setObject:[responseObject objectForKey:#"fid"] forKey:#"fid"];
[file removeObjectForKey:#"file"];
fid = [responseObject objectForKey:#"fid"];
NSLog(#"%#",responseObject);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject: [NSString stringWithFormat:#"%#", fid] forKey:#"fid"];
NSLog(#"%#", fid);
NSDictionary *fidLangDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:dict] forKey:#"und"];
[nodeData setObject:fidLangDict forKey:#"field_photo"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Node did not save!");
}];
[DIOSFile fileSave:file success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"File uploaded!");
//SECOND IMAGE FILE
[secondfile setObject:[responseObject objectForKey:#"fid"] forKey:#"fid"];
[secondfile removeObjectForKey:#"file"];
fid = [responseObject objectForKey:#"fid"];
NSLog(#"%#",responseObject);
NSMutableDictionary *secondDict = [NSMutableDictionary dictionary];
[secondDict setObject: [NSString stringWithFormat:#"%#", fid] forKey:#"fid"];
NSLog(#"%#", fid);
NSDictionary *secondfidLangDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:secondDict] forKey:#"und"];
[nodeData setObject:secondfidLangDict forKey:#"phototwo"];
[DIOSNode nodeSave:nodeData success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Node saved!");
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main_iPad" bundle:nil];
ipadaccountViewController *AccountViewController = (ipadaccountViewController *)[storyboard instantiateViewControllerWithIdentifier:#"MyAccount"];
[self.navigationController popViewControllerAnimated:TRUE];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Node did not save!");
}];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Node did not save!");
}];
XML Data upon save:
<field_photo>
<und is_array="true">
<item>
<fid>265</fid>
<uid>5</uid>
<filename>phone.jpg</filename>
<uri>public://stored/phone_1.jpg</uri>
<filemime>image/jpeg</filemime>
<filesize>161858</filesize>
<status>1</status>
<timestamp>1460264800</timestamp>
<rdf_mapping/>
<alt/>
<title/>
<width>1536</width>
<height>1536</height>
</item>
</und>
</field_photo>
<phototwo>
<und is_array="true">
<item>
<fid>266</fid>
<uid>5</uid>
<filename>phone.jpg</filename>
<uri>public://stored/phone_2.jpg</uri>
<filemime>image/jpeg</filemime>
<filesize>161858</filesize>
<status>1</status>
<timestamp>1460264800</timestamp>
<rdf_mapping/>
<alt/>
<title/>
<width>1536</width>
<height>1536</height>
</item>
</und>
</phototwo>
I think in the second [DIOSFile fileSave... it should be secondfile instead of file.

Capture Upload Image Failed iOS

I m trying to upload image through AFNetworking.
Following is the way I try to save image in an array. Image uploading starts, but right after the 1.1% of upload it stops uploading without any error. No Idea what is happening.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
NSData *imageData=UIImagePNGRepresentation(chosenImage);
ImageObject *imageObject=[[ImageObject alloc]init];
imageObject.image=chosenImage;
imageObject.imageData=imageData;
imageObject.imageUploadStatus=FALSE;
imageObject.isUploaded=FALSE;
[imageObject setDescription:#""];
[imageDataArray addObject:imageObject];
}
After this I upload image with Following method.
-(void)uploadPicturesAndVides:(NSMutableArray *)_list descriptions:(NSMutableArray *)_description categoryID:(NSString *)_catID categoryName:(NSString *)_categoryName index:(NSInteger)_index{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:[SettingValues getRSFToken] forHTTPHeaderField:#"_csrf"];
[manager.requestSerializer setValue:#"USER_Agent_Value" forHTTPHeaderField:#"User-Agent"];
NSString *imageUrl;
imageUrl=[NSString stringWithFormat:#"%#/user/upload/photo",BASE_SERVER_ADDRESS];
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
for (ImageObject *object in _list) {
[tempArray addObject:[object description]];
}
NSString *descriptions;
descriptions=[tempArray componentsJoinedByString:#","];
NSDictionary *parameters = #{#"descriptionImage":descriptions,#"subcategoryId":_catID,#"subcategoryName":_categoryName,#"_csrf": [SettingValues getRSFToken]};
AFHTTPRequestOperation *op = [manager POST:imageUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSInteger count=_index;
for (ImageObject *object in _list) {
NSString *imageName = [NSString stringWithFormat:#"IMG00%zd.png",count];
[formData appendPartWithFileData:object.imageData name:#"files" fileName:imageName mimeType:#"image/png"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
[SettingValues setImageUploadStatus:TRUE];
[self uploadingRequestSuccessfulWithObject:responseObject reqestName:#"picture" index:_index];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[op setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
[self goBackTouploadingControllerWithProgressResult:percentDone index:_index];
}];
cancelManager=op;
[op start];
}
Following is the image and its progress stays here! no success no failure. :(
Problem is that code works when I upload image through Camera Roll, But when I capture image, it did not.
I put a NSLog(#"progress updated(percentDone) : %f", percentDone); in Progress Block and I found the following logs
2015-02-07 13:07:22.854 APP_Name[2069:60b] progress updated(percentDone) : 0.002105
2015-02-07 13:07:22.858 APP_Name[2069:60b] progress updated(percentDone) : 0.004210
2015-02-07 13:07:22.860 APP_Name[2069:60b] progress updated(percentDone) : 0.006315
2015-02-07 13:07:22.861 APP_Name[2069:60b] progress updated(percentDone) : 0.008413
and then every thing stops.
In Failure block I put following log
NSLog(#"Error: %# ***** %#", operation.responseString, error);
Never executed :(

AFNetworking not uploading image

I am trying to upload an image via AFnetworking. I am able to get the image url, and it does contact my server. However, it won't upload. The file upload folder is empty and when I get back my JSON response, it is "null"
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Request to save the image to camera roll
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"error");
} else {
NSLog(#"url %#", assetURL);
NSData *data = [NSData dataWithContentsOfURL:assetURL];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingString:#"/image.jpg"];
[data writeToFile:path atomically:YES];
[self uploadPhoto:path];
// NSLog(path);
[self dismissModalViewControllerAnimated:NO];
}
}];
}
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": self.targetid};
NSURL *filePath = [NSURL fileURLWithPath:file];
[manager POST:#"http:/****/uploadpics.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
image url looks like this:
/var/mobile/Applications/FFCAE923-1115-4209-AB39-D9D1ACEB9CB7/Documents/yourLocalImage.png
I can't seem to figure out what am I doing wrong.. The script is fine because it works for android just as it is supposed to...
PHP:
$name = $_FILES['filename']['name'];
if (is_uploaded_file($_FILES['filename']['tmp_name'])){
if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES ['filename'] ['name'])) {
Echo $foname;
} else {
}
} else {
}
Your upload code names the file image but your script seems to expect filename. I haven't done any php for a while but I think they should match.
There is another method which allows you to specify more details about the part that you're appending to the form data so you probably need that to set the appropriate names.

Resources