I tried below code to upload video with Multi part form POST in AFnetworking but when uploading, video sent about 80% is broken. This is my code:
-(void) uploadVideoAPI: (NSString*) emailStr andSumOfFiles: (NSString*) sumSizeFile andVideoNams:(NSMutableArray*) videoNameArr andUpFile :(NSMutableArray *) videoDataArray
{
NSURL *url = [NSURL URLWithString:#"http://myserver.com];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: url] ;
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:nil parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) {
[formData appendPartWithFormData:[emailStr dataUsingEncoding:NSUTF8StringEncoding]
name:#"emailStr"]; //parametters1
[formData appendPartWithFormData:[sumSizeFile dataUsingEncoding:NSUTF8StringEncoding] name:#"sumSizeFile"];//parametters 2
for(int i=0;i<[videoDataArray count];i++)
{
NSString * videoName = [videoNameArr objectAtIndex:i];
NSData *videoData = [videoDataArray objectAtIndex:i];
[formData appendPartWithFileData:videoData
name:#"videos"
fileName:videoName mimeType:#"video/quicktime"];
}
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Upload Complete");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
NSLog(#"%#",error);
}];
[operation start];
}
My code has any problem? Please give me some advice. thanks in advance
I suggest you to use appendPartWithFileURL instead of appendPartWithFormData for files, to avoid memory problems (imagine big data like video or compressed data files).
I use something like this:
// Create request
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:nil parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) {
// Important!! : file path MUST BE real file path (so -> "file://localhost/.../../file.txt") so i use [NSURL fileURLWithPath:]
NSError* err;
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filePathToUpload] name:[fileInfo objectForKey:#"fileName"] error:&err];
}];
Related
I having problem with downloading array of images from server, if i have 100 images on server means i should download all images using "AFImageRequestOperation", while downloading process some images are downloaded successfully but many images are failed to download because of "TimeOut" error from server,i facing Timeout issue with large size image(3.mb),
i using follwing way to downloading images:
NSURL *url = [NSURL URLWithString:kBaseURLString];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setAuthorizationHeaderWithUsername:[[NSUserDefaults standardUserDefaults] stringForKey:kUserDefaultKeyUsername]
password:[[NSUserDefaults standardUserDefaults] stringForKey:kUserDefaultKeyPassword]];
for( int i = 0; i < [self.downloadImageList count]; i++ ) {
NSString *filename = [[NSString alloc] initWithString:[self.downloadImageList objectAtIndex:i]];
NSMutableURLRequest *urlRequest = [httpClient multipartFormRequestWithMethod:#"POST"
path:#"/xxx/yyyyyyyyyy/getImage"
parameters:nil
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFormData:[filename dataUsingEncoding:NSUTF8StringEncoding]
name:kFormNameFile];
}];
AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
[requestOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
[self updateSyncClientUIDelegateProgress:(totalBytesRead/totalBytesExpectedToRead) andLabel:#"Downloading Images"];
}];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if( [[urlRequest URL] isEqual:[[operation request] URL]] ) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = responseObject;
NSLog(#"Downloading image %#",image);
[UIImagePNGRepresentation(image) writeToFile:[syncedImagesPath stringByAppendingPathComponent:filename] atomically:YES];
});
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if( [[operation response] statusCode] == 404 ) {
return;
}
NSLog(#"failure BLOCK %#",error);
NSLog(#"failure error code %ld",(long)[error code]);
if( [error code] != NSURLErrorCannotDecodeContentData ) {
[self cancelSyncFromFailure];
}
}];
Please help me to fix this timeout issue while downloading large iamges
NOW HERE IS THE SOLUTION I AM USING AND WORKING FINE.FIRSTLY IT WAS ALSO SENDING ME THE "REQUEST TIMEOUT" MESSAGE BUT NOT NOW.TRY THIS
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:photourl] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10000];
AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
[requestOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
...... YOUR CODE
}];
You set TimeOut Request Time is more a below code.
[urlRequest setTimeoutInterval:50];
Hello i am new to afnetworking, i want to upload image at server path from ios sdk. below is code for afnetworking,
NSData *imageToUpload = UIImageJPEGRepresentation(selectedImageView.image, 90);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://192.168.0.100//smart_attendance/api/employeeImage.php"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"employee_images/large/" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
// [MBProgressHUD hideHUDForView:self.view animated:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//[MBProgressHUD hideHUDForView:self.view animated:YES];
if([operation.response statusCode] == 403){
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [operation error]);
}];
[operation start];
SERVER RESPONSE IS
AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest
http://192.168.0.102/trackingwebsite/tree_images/large/>,
NSErrorFailingURLKey=http://192.168.0.102/trackingwebsite/tree_images/large/,
NSLocalizedDescription=Expected status code in (200-299), got 404,
AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x98671e0>}
Try out this for url.
NSString *imgUrl=[imageURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:imgUrl];
Also your path string is not proper i guess.
Hope that helps.
welll i am using this way and its working fine.
NSString* imageName = #"_image.png";
[[AFAPIClient sharedClient]initWithBaseURL:[NSURL URLWithString:BaseUrl]];
NSMutableURLRequest *request = [[AFAPIClient sharedClient] multipartFormRequestWithMethod:#"POST" path:[NSString stringWithFormat:#"%#%#",BaseUrl,sign_up.php] parameters:dict constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:UIImagePNGRepresentation([dict objectForKey:#"image"]) name:#"image" fileName:imageName mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];
[[AFAPIClient sharedClient]enqueueHTTPRequestOperation:operation];
[operation release];
edited
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://192.168.0.100/smart_attendance/api/employeeImage.php"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"http://192.168.0.100/smart_attendance/api/employeeImage.php"
parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageToUpload name:#"file" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
}];
I have an example, where I send image and parameters to server. But I need to send NSArray of images.How can I do this?
NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
if (imageToUpload)
{
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, #"keyName", nil];
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://------"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"API name as you have" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"image" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
//NSLog(#"response: %#",jsons);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if([operation.response statusCode] == 403)
{
//NSLog(#"Upload Failed");
return;
}
//NSLog(#"error: %#", [operation error]);
}];
[operation start];
}
Help me, please!
I found an answer, I changed my code to this:
[formData appendPartWithFileData:data name:#"Photos[1]" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
[formData appendPartWithFileData:data name:#"Photos[2]" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
and server understand it as array
You can try this,
NSURL *url = [NSURL URLWithString:#URL_BASE];
int count = [imageArray count];
for(int i = 0; i < count; ++i)
{
UIImage* image = [imageArray objectAtIndex:i];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: image.size.width], #"width",
[NSNumber numberWithFloat: image.size.height], #"height",
nil];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#PATH_ALBUM_IMAGE_UPLOAD parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"file%d", i] fileName:#"avatar.jpg" mimeyTpe:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
[progressView setProgress: totalBytesWritten*1.0f / totalBytesExpectedToWrite animated: YES];
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
if(totalBytesWritten >= totalBytesExpectedToWrite)
{
progressView.hidden = YES;
}
}];
[operation start];
}
Here's the problem :
I want to upload image immediately after finish choosing image from imagepicker.
So, I put my code to upload image using afnetworking in imagepicker delegate method.
But it doesn't response anything.
//set the imageview to current image after choosing
profilePic.image = image;
//dismiss the imagepicker
[picker dismissModalViewControllerAnimated:YES];
//start upload image code
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"steventi1901", #"username",
UIImagePNGRepresentation(profilePic.image), #"profile_pic",
nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:updateProfile];
NSData *imageToUpload = UIImagePNGRepresentation(profilePic.image);
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"PUT" path:#"" parameters:params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:#"temp.png" mimeType:#"image/png"];
//NSLog(#"dalem");
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([operation.response statusCode] == 403){
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [operation error]);
}];
[operation start];
//end upload image code
It really didn't response anything so i didn't know if the process fail or success.
Best and Easy way to upload Image using Afnetworking.
Please use below AFNetworking.
pod 'AFNetworking', '~> 2.5.4'
//Create manager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//parameters if any
NSMutableDictionary *AddPost = [[NSMutableDictionary alloc]init];
[AddPost setValue:#"Addparma" forKey:#"param"];
NSString * url = [NSString stringWithFormat:#"www.addyourmainurl.com"];;
NSLog(#"AddPost %#",AddPost);
[manager POST:url parameters:[AddPost copy] constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//add image data one by one
for(int i=0; i<[Array count];i++)
{
UIImage *eachImage = [Array objectAtIndex:i];
NSData *imageData = UIImageJPEGRepresentation(eachImage,0.5);
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"image%d",i] fileName:[NSString stringWithFormat:#"image%d.jpg",i ] mimeType:#"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
have you set the delegate of the picker?
[yourPicker setDelegate:self]
NSURL *url = [NSURL URLWithString:#"http://127.0.0.1:8000/photo/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *headers = [NSDictionary dictionaryWithObject:data forKey:#"attachment"];
//NSLog(#"strimng");
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"upload/" parameters:nil constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) {
NSLog(#"strimng");
[formData appendPartWithFileData:data name:#"attachment" fileName:#"attachment.jpg" mimeType:#"image/jpeg"];
NSLog(#"strimng");
}];
NSLog(#"strimng");
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];
I am Trying to upload the image from the iphone using AFNetworking, but this is not working.
The NSLog just before formdata appenddata command is logged out. But the one after that doesnt seem to. I have also checked if NSdata is nil and thats also not the case. And obv the request is not being sent.
Please can anyone help me.
Assuming that you have to upload an image, why are you creating an NSDictionary with the data? It is not necessary, you just need to use data inside multipartFormRequestWithMethod.
Try the following
// Get the image that you want to upload via ImagePicker or a #property
UIImage *imageIWantToUpload = self.image;
// Create the NSData object for the upload process
NSData *dataToUpload = UIImageJPEGRepresentation(imageIWantToUpload, 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"upload/" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:dataToUpload name:#"attachment" fileName:#"attachment.jpg" mimeType:#"image/jpg"];
}];
// You can add then the progressBlock and the completionBlock
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:progress];
[operation setCompletionBlockWithSuccess:success failure:failure];
You should also double check if your server side expects some parameters, because you are setting the NSMutableURLRequest parameters' field to nil.