iOS开发之AFNetworking图片上传
AFNetworking是一个讨人喜欢的网络库,适用于iOS以及Mac OS X.
图片上传是许多app 都会用到的,常用网路库AFNetworking是怎样上传图片的了?这是我在开发中碰到的,分享给大家。
//添加宝宝
- (void) UploadPictureByFileName:(NSString*) fileName
Path:(NSString*) path
Baby:(ChildrenModel *)babyModel
UserID:(NSInteger) userID
block:(void (^)(NSString *namePath,NSInteger result, NSString *message, NSError *error))block {
NSString *url =@"https://www.umakeme.cn/schedule/";
NSString *urlString=[NSString stringWithFormat:@"%@%@",url,@"us/add_modify_kid/"];
NSDictionary *parameters = nil;
parameters = @{@"id":[NSNumber numberWithInteger:userID],
@"username":babyModel.username?babyModel.username:@"",
@"nickname":babyModel.nickname?babyModel.nickname:@"",
@"logo":babyModel.logo?babyModel.logo:@"",
@"gender":[NSNumber numberWithInteger:babyModel.gender?babyModel.gender :1],
@"birth":babyModel.birth?babyModel.birth:@"",
@"bgimg":babyModel.bgimg?babyModel.bgimg:@"0",
@"status":[NSNumber numberWithInteger:babyModel.Status?babyModel.Status:0]
};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//得到需要上传的数据
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *upfileName = [NSString stringWithFormat:@"%@.jpg",fileName];
/*
此方法参数
1. 要上传的[二进制数据]
2. 对应网站上[upload.php中]处理文件的[字段"file"]
3. 要保存在服务器上的[文件名]
4. 上传文件的[mimeType]
*/
//服务器上传文件的字段和类型
[formData appendPartWithFileData:data name:@"logo" fileName:upfileName mimeType:@"image/jpg/file"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSInteger retCode = [[responseObject valueForKeyPath:@"err"]integerValue];
NSLog(@"--------*--添加宝宝/修改宝宝-*---------json:%@",responseObject);
if (block) {
block(@"",retCode,@"", nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (block) {
block(@"",-1,@"上传错误",error);
}
NSLog(@"上传错误:%@",error);
}];
}