AFNetworking是一個討人喜歡的網絡庫,適用於iOS以及Mac OS X.php
圖片上傳是許多app 都會用到的,經常使用網路庫AFNetworking是怎樣上傳圖片的了?這是我在開發中碰到的,分享給你們。json
//添加寶寶服務器
- (void) UploadPictureByFileName:(NSString*) fileName網絡
Path:(NSString*) pathapp
Baby:(ChildrenModel *)babyModel網站
UserID:(NSInteger) userIDurl
block:(void (^)(NSString *namePath,NSInteger result, NSString *message, NSError *error))block {spa
NSString *url =@"https://www.umakeme.cn/schedule/";orm
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);
}];
}