iOS开发中关于图片上传,一般有两种方法:
1.自己手动写(如:NSURLMutableRequest等系统类),实现起来比较复杂,暂且不提
2.使用第三方(如:主流的AFNetworking),在开发中使用第三方比较多,下面就是使用AFN上传图片的流程:
//获取图片
-(void)avatarTap:(id)sender{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"设置头像" message:@"" preferredStyle:UIAlertControllerStyleAlert];
//取消
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
}];
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
imagePicker.allowsEditing = YES;
imagePicker.delegate = self;
//从相册中选择
UIAlertAction* fromPhotosAlbumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:imagePicker animated:YES completion:nil];
}];
//从图库选择
UIAlertAction* fromPhotoAction = [UIAlertAction actionWithTitle:@"从图库选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagePicker animated:YES completion:nil];
}];
//相机拍摄
UIAlertAction* fromCameraAction = [UIAlertAction actionWithTitle:@"相机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePicker animated:YES completion:nil]; }
}];
[alertController addAction:cancelAction];
[alertController addAction:fromCameraAction];
[alertController addAction:fromPhotoAction];
[alertController addAction:fromPhotosAlbumAction];
[self presentViewController:alertController animated:YES completion:nil];
}
//如何进行压缩
//将图片尺寸改为240x240
UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(240.0f, 240.0f)];
//写入jpg文件
[UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];
//+ (UIImage *)imageWithCGImage:(CGImageRef)cgImage scale:(CGFloat)scale orientation:(UIImageOrientation)orientation NS_AVAILABLE_IOS(4_0);**
//该方法使用一个CGImageRef创建UIImage,在创建时还可以指定放大倍数以及旋转方向。当scale设置为1的时候,新创建的图像将和原图像尺寸一摸一样,而orientaion则可以指定新的图像的绘制方向。
//也可以用这个方法进行压缩你会发现得到的大小会小了很多倍,如果想测试的话可以转换成 NSData 打印一下。
//获取压缩后的图片
+ (UIImage *) scaleFromImage: (UIImage *) imagetoSize: (CGSize)size{
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
#pragma mark - 图片上传
//上传图片(单张)
+(void)uploadPhotoAndController:(UIViewController *)controller WithSize:(CGSize)size Image:(UIImage*)image AndFinish:(void (^)(NSDictionary *, NSError *))finish
{
//加载提示菊花
MBProgressHUD *hud;
if(controller){
hud = [MBProgressHUD showHUDAddedTo:controller.view animated:YES];
hud.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
}
//1. 存放图片的服务器地址,这里我用的宏定义
NSString * url = [NSString stringWithFormat:@"%@%@",Hx_Main_heard_API,IMAGE_UPLOAD_URL_API];
//2. 利用时间戳当做图片名字
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *imageName = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg",imageName];
//3. 图片二进制文件
NSData *imageData = UIImageJPEGRepresentation(image, 0.7f);
NSLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
//4. 发起网络请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 上传图片,以文件流的格式,这里注意:name是指服务器端的文件夹名字
[formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//上传成功时的回调
[hud hideAnimated:YES];
NSLog(@"%@",responseObject);
finish(responseObject,nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//失败时的回调
[hud hideAnimated:YES];
finish(nil,error);
}];
}
// 上传图片(多张)
+(void)uploadPhotoAndController:(UIViewController *)controller WithSize:(CGSize)size Image:(UIImage*)image AndFinish:(void (^)(NSDictionary *, NSError *))finish
{
//加载提示菊花
MBProgressHUD *hud;
if(controller){
hud = [MBProgressHUD showHUDAddedTo:controller.view animated:YES];
hud.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
}
//1. 存放图片的服务器地址,这里我用的宏定义
NSString * url = [NSString stringWithFormat:@"%@%@",Hx_Main_heard_API,IMAGE_UPLOAD_URL_API];
//2. 发起网络请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
// 上传多张图片
for(NSInteger i = 0; i < self.imageDataArray.count; i++)
{
//取出单张图片二进制数据
NSData * imageData = self.imageDataArray[i];
// 上传的参数名,在服务器端保存文件的文件夹名
NSString * Name = [NSString stringWithFormat:@"%@%ld", Image_Name, i+1];
// 上传filename
NSString * fileName = [NSString stringWithFormat:@"%@.jpg", Name];
[formData appendPartWithFileData:imageData name:Name fileName:fileName mimeType:@"image/jpeg"];
}
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
//上传成功时的回调
[hud hideAnimated:YES];
NSLog(@"%@",responseObject);
finish(responseObject,nil);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
//失败时的回调
[hud hideAnimated:YES];
finish(nil,error);
}];
}
网友评论