iPhone Upload Multipart File Using Afnetworking

iPhone upload multipart file using AFNetworking

Looking at your HTML, the name of your is files, and thus, you would use @"files" as the name parameter to the appendPartWithFileData method. For example, with AFNetworking 3.x:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileData:imageData
name:@"files"
fileName:photoName mimeType:@"image/jpeg"];

[formData appendPartWithFormData:[key1 dataUsingEncoding:NSUTF8StringEncoding]
name:@"key1"];

[formData appendPartWithFormData:[key2 dataUsingEncoding:NSUTF8StringEncoding]
name:@"key2"];

// etc.
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: %@", error);
}];

(For AFNetworking 1.x and 2.x syntax, see the revision history of this answer.)

multipart PUT request using AFNetworking

You can use multipartFormRequestWithMethod to create a multipart PUT request with desired data.

For example, in AFNetworking v3.x:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

NSError *error;
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:@"http://example.com/rest/api/" parameters:@{@"foo" : @"bar"} constructingBodyWithBlock:^(id formData) {
NSString *value = @"qux";
NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:@"baz"];
} error:&error];

NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", error);
return;
}

// if you want to know what the statusCode was

if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
NSLog(@"statusCode: %ld", statusCode);
}

NSLog(@"%@", responseObject);
}];
[task resume];

If AFNetworking 2.x, you can use AFHTTPRequestOperationManager:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSError *error;
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:@"http://example.com/rest/api/" parameters:@{@"foo" : @"bar"} constructingBodyWithBlock:^(id formData) {
NSString *value = @"qux";
NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:@"baz"];
} error:&error];

AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];

[manager.operationQueue addOperation:operation];

Having illustrated how one could create such a request, it's worth noting that servers may not be able to parse them. Notably, PHP parses multipart POST requests, but not multipart PUT requests.

Upload multiple Image or File using AFNetworking,

Check this method from AFURLSessionManager:

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler

Full code implementation:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

[[sessionManager uploadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@BaseURL(@"/MediaUpload")]]
fromFile:[NSURL fileURLWithPath:@"/path/to/uploading_file"]
progress:^(NSProgress * _Nonnull uploadProgress) { }
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
}] resume];

How to Upload Multipart data of image in base64 Using afnetworking

You can just use the appendPartWithFileData:name:fileName:mimeType: method of the AFMultipartFormData class.

For instance:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

[manager POST:@"https://blahblahblah.com/imageupload" parameters:nil constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileData:imageData
name:@"key name for the image"
fileName:photoName mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: %@", error);
}];

AFNetworking 3.0 Multipart form data for uploading image error

Use this method

-(void)callWebserviceToUploadImageWithParams:(NSMutableDictionary *)_params imgParams:(NSMutableDictionary *)_imgParams videoParms:(NSMutableDictionary *)_videoParams action:(NSString *)_action success:(void (^)(id))_success failure:(void (^)(NSError *))_failure

{
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
//Here BASE_URL is my URL of web service
NSString *urlString = [BASE_URL stringByAppendingString:_action];
NSLog(@"URL : %@",urlString);
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlString]];
[urlRequest setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[urlRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
// [urlRequest setValue:contentType forHTTPHeaderField:@"Content-type: application/json"]
NSMutableData *body = [NSMutableData data];
[_params enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSString *object, BOOL *stop) {
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",object] dataUsingEncoding:NSUTF8StringEncoding]];
}];
[_imgParams enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSData *object, BOOL *stop) {
if ([object isKindOfClass:[NSData class]]) {
if (object.length > 0) {
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"Timestamp:%@",TimeStamp);
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpg\"\r\n",key,TimeStamp] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:object]];
}

}
}];
[_videoParams enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSData *object, BOOL *stop) {
if (object.length > 0) {
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"Timestamp:%@",TimeStamp);
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.mp4\"\r\n",key,TimeStamp] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:object]];
}
}];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:body];
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = nil;


NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
if( _failure )
{
_failure( error) ;
}
} else {
if( _success )
{
_success( responseObject ) ;
}
}
}];
[dataTask resume];
}
else
{
[Utility showInterNetConnectionMessage];
NSError *error;
if( _failure )
{
_failure( error) ;
}
}
}

If you are not uploading any video or image then give as nil

USE:

#pragma -mark callwebservice for login
-(void)callWebserviceFor_upload_Sticker {
// Check whether Company user login or Individual User login.
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];

//user_id, user_token, emoji_weburl(optional), emoji_picture(file)
NSMutableDictionary *dict_user_data = [Utility getUserPlistData];
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:[dict_user_data valueForKey:@"user_id"] forKey:@"user_id"];
[params setValue:[dict_user_data valueForKey:@"user_token"] forKey:@"user_token"];
NSLog(@"%@",params);

NSMutableDictionary *imgParams = [[NSMutableDictionary alloc]init];
[imgParams setValue:UIImageJPEGRepresentation(img_to_upload, 0) forKey:@"emoji_picture"];

void ( ^successed )( id _responseObject ) = ^( id _responseObject )
{
NSLog(@"%@",_responseObject);
//Your logic after success
} ;
void ( ^failure )( NSError* _error ) = ^( NSError* _error ) {
[SVProgressHUD showErrorWithStatus:@"Failed"];
} ;

[[WebServiceHendler sharedManager]callWebserviceToUploadImageWithParams:params imgParams:imgParams videoParms:nil action:UPDATE_EMOJI success:successed failure:failure];
}

Uploading an image using AFNetworking 3.0

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

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];

In this code http://example.com/upload is api where image is going to upload and file://path/to/image.jpg is your local image path.

Upload multiple images using AFNetworking

UIImage *image1 = [UIImage imageNamed:@"about_app"];
UIImage *image2 = [UIImage imageNamed:@"alter"];
NSArray *array = @[image1,image2];
NSMutableURLRequest *request = [[AFNetWorkSingleton shareInstance] multipartFormRequestWithMethod:@"POST" path:@"Mindex/getimg" parameters:nil constructingBodyWithBlock:^(idformData){
int i = 0;
for(UIImage *eachImage in array)
{
NSData *imageData = UIImageJPEGRepresentation(eachImage,0.5);
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",i ] fileName:[NSString stringWithFormat:@"file%d.jpg",i ] mimeType:@"image/jpeg"];
i++;
}
}];

Try this.



Related Topics



Leave a reply



Submit