美文网首页iOS开发iOS开发进阶手机移动程序开发
iOS 将图片(单张或多张)上传至阿里云详解

iOS 将图片(单张或多张)上传至阿里云详解

作者: honey缘木鱼 | 来源:发表于2018-06-04 18:22 被阅读34次

一.准备工作
1.上阿里云的网站里下载sdk:网址为:https://help.aliyun.com/document_detail/32060.html?spm=5176.doc32059.6.296.QgohfC。demo地址 https://github.com/aliyun/aliyun-oss-ios-sdk

  1. 把demo中的AliyunOSSiOS.framework拖入工程
  2. 导入头文件#import <AliyunOSSiOS/OSSService.h>
  3. 初始化阿里云@property (strong, nonatomic) OSSClient *client;

二.直接讲解封装好的上传阿里云的文件
1.AliyunOSSUpload.h文件

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#define AliyunUpload                [AliyunOSSUpload aliyunInit]
typedef enum{
    ENT_fileImageHeader,//头像
    ENT_fileImageBody,//个人图片
    ENT_fileImageProject,//门店图片
    ENT_fileImageJs,//技师展示图片
    ENT_fileItemImageBody,//门店项目图片
}FileType;
@interface AliyunOSSUpload : NSObject

+(AliyunOSSUpload *)aliyunInit;

-(void)uploadImage:(NSArray*)imgArr   FileDirectory:(FileType)type  success:(void (^)(NSString *obj))success;
@end

根据公司需要上面我定义一个枚举,返回不同图片的大小。

2.AliyunOSSUpload.m文件

#import <AliyunOSSiOS/OSSService.h>
#import <AliyunOSSiOS/OSSCompat.h>
#import "AliyunOSSUpload.h"
//#import "NSObject+SBJSON.h"
NSString * const AccessKey = @"***";
NSString * const SecretKey = @"***";
NSString * const endPoint = @"https://oss-cn-qingdao.aliyuncs.com/";

OSSClient * client;
@implementation AliyunOSSUpload
static AliyunOSSUpload *_config;

+(AliyunOSSUpload *)aliyunInit{
    @synchronized(self){
        if (_config==nil) {
            [OSSLog enableLog];
            
            _config=[[AliyunOSSUpload alloc] init];
            id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey
                                                                                                                    secretKey:SecretKey];
            
            
            client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
        }
    }
    return _config;
}



-(void)uploadImage:(NSArray*)imgArr   FileDirectory:(FileType)type  success:(void (^)(NSString *obj))success{
    NSMutableArray *imgArray=[NSMutableArray new];
    for (int i=0; i<imgArr.count; i++) {
        NSData* data;
        
        NSDictionary *imgDictionary = [imgArr objectAtIndex:i];
        NSArray *imgValue = [imgDictionary allValues];
        NSArray *imgKey = [imgDictionary allKeys];
        UIImage *image1 = [imgValue objectAtIndex:0];
        NSString *str = [imgKey objectAtIndex:0];
        UIImage *image=[IHUtility rotateAndScaleImage:image1 maxResolution:(int)kScreenWidth*2];
        OSSPutObjectRequest * put = [OSSPutObjectRequest new];
        put.contentType=@"image/jpeg";
        put.bucketName = @"yijiao";
        NSString *imgName;
        if (type==ENT_fileImageHeader) {
            NSData *data1=UIImageJPEGRepresentation(image, 1);
            float length1 = [data1 length]/1024;
            if (length1<600) {
                data = UIImageJPEGRepresentation(image, 1);
            }else{
                if ([IHUtility IsEnableWIFI]) {
                    data = UIImageJPEGRepresentation(image, 0.6);
                }else{
                    data = UIImageJPEGRepresentation(image, 0.5);
                }
            }
            
            imgName=[NSString stringWithFormat:@"ios/header/header_%@.jpg",[IHUtility getTransactionID]];
        }else if (type==ENT_fileImageBody){
            NSData *data1=UIImageJPEGRepresentation(image, 1);
            float length1 = [data1 length]/1024;
            if (length1<600) {
                data = UIImageJPEGRepresentation(image, 1);
            }else{
                data = UIImageJPEGRepresentation(image, 0.5);
            }
            imgName=[NSString stringWithFormat:@"ios/content/body_%@/%@.jpg",str,[IHUtility getNowTimeTimestamp]];
        }else if (type==ENT_fileImageJs)
        {
            NSData *data1=UIImageJPEGRepresentation(image, 1);
            float length1 = [data1 length]/1024;
            if (length1<600) {
                data = UIImageJPEGRepresentation(image, 1);
            }else{
                data = UIImageJPEGRepresentation(image, 0.5);
                
            }
            imgName=[NSString stringWithFormat:@"js/header/header_%@.jpg",[IHUtility getTransactionID]];
        }else if (type==ENT_fileImageProject){
            NSData *data1=UIImageJPEGRepresentation(image, 1);
            float length1 = [data1 length]/1024;
            if (length1<600) {
                data = UIImageJPEGRepresentation(image, 1);
            }else{
                data = UIImageJPEGRepresentation(image, 0.5);
            }
            imgName=[NSString stringWithFormat:@"ios/storePicture/web_%@/%@.jpg",str,[IHUtility getNowTimeTimestamp]];
        }else if (type==ENT_fileItemImageBody){
            NSData *data1=UIImageJPEGRepresentation(image, 1);
            float length1 = [data1 length]/1024;
            if (length1<600) {
                data = UIImageJPEGRepresentation(image, 1);
            }else{
                data = UIImageJPEGRepresentation(image, 0.5);
            }
            imgName=[NSString stringWithFormat:@"ios/web/itemBody_%@/%@.jpg",str,[IHUtility getNowTimeTimestamp]];
        }
        put.objectKey = imgName;
        put.uploadingData = data; // 直接上传NSData
        
        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
        };
        
        NSString *imgWidth;
        NSString *imgHeigh;
        if (type==ENT_fileImageHeader) {
            imgWidth=[NSString stringWithFormat:@"%d",(int)kScreenWidth];
            imgHeigh=[NSString stringWithFormat:@"%d",(int)kScreenWidth];
            
        }
        else if (type==ENT_fileImageBody){
            imgWidth=[NSString stringWithFormat:@"%lf",image.size.width];
            imgHeigh=[NSString stringWithFormat:@"%lf",image.size.height];
        } else if (type==ENT_fileImageJs){
            imgWidth=[NSString stringWithFormat:@"%lf",image.size.width];
            imgHeigh=[NSString stringWithFormat:@"%lf",image.size.height];
        }else if (type==ENT_fileImageProject){
            imgWidth=[NSString stringWithFormat:@"%lf",image.size.width];
            imgHeigh=[NSString stringWithFormat:@"%lf",image.size.height];
        }else if (type==ENT_fileItemImageBody){
            imgWidth=[NSString stringWithFormat:@"%lf",image.size.width];
            imgHeigh=[NSString stringWithFormat:@"%lf",image.size.height];
        }
        
        NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"/%@",imgName],@"t_url",
                           imgWidth,@"t_width",
                           imgHeigh,@"t_height",
                           nil];
        [imgArray addObject:dic];
        
        if (client==nil) {
            id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey
                                                                                                                    secretKey:SecretKey];
            
            client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
        }
        
        OSSTask * putTask = [client putObject:put];
        
        [putTask continueWithBlock:^id(OSSTask *task) {
            if (!task.error) {
                NSLog(@"upload object success!");
                if (type==ENT_fileImageHeader) {
                    NSString *str=[NSString stringWithFormat:@"/%@",imgName];
                    success(str);
                }
                else if (type==ENT_fileImageBody){
                    if (i==imgArr.count-1) {
                        NSString *str=[imgArray JSONRepresentation];
                        success(str);
                    }
                }else if (type==ENT_fileImageJs){
                    success(imgName);
                }
                else if (type==ENT_fileImageProject){
                    if (i==imgArr.count-1) {
                        NSString *str=[imgArray JSONRepresentation];
                        success(str);
                    }
                }else if (type==ENT_fileItemImageBody){
                    success(imgName);
                }
            } else{
                [YJTipView showBottomWithText:@"图片上传失败,请重试" bottomOffset:300 duration:1.5f];
                NSLog(@"upload object failed, error: %@" , task.error);
            }
            return nil;
        }];
    }
}

想上传到阿里,首先要有对应的阿里的账号参数,填写到这里

NSString * const AccessKey = @"";

NSString * const SecretKey = @"";

OSSClient是OSS服务的iOS客户端,它为调用者提供了一系列的方法,用于和OSS服务进行交互。一般来说,全局内只需要保持一个OSSClient,用来调用各种操作。

Bucket名称, Object名称

 put.bucketName = @"自己的数据";

 put.objectKey = @"自己的数据";

data上传

put.uploadingData = self.imageData;//自己的NSData数据

上传的时候你也可以看一看你的上传进度,还有一些参数配置

put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//当前上传段长度、当前已经上传总长度、一共需要上传的总长度
        };

我没有按照官方说的加上这句:

task = [client presignPublicURLWithBucketName:@"同上面的bucketName"

withObjectKey:同上];

因为上传阿里云的时候,上传的图片命名不能相同,所以利用了随机数,和时间戳的方法

随机数方法:

//随机数
+ (NSString*)getTransactionID
{
    NSDate* date = [NSDate date];
    NSMutableString* strDate = [NSMutableString stringWithFormat:@"%@", date];
    NSString *s1=[strDate stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSString *s2= [s1 stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *s3= [s2 stringByReplacingOccurrencesOfString:@":" withString:@""];
    int n = (arc4random() % 9000) + 1000;
    NSMutableString* transactionID = [NSMutableString stringWithString:[s3 substringToIndex:14]];
    [transactionID appendString:[NSString stringWithFormat:@"%d", n]];
    
    [transactionID stringByReplacingOccurrencesOfString:@" " withString:@""];
    return transactionID;
}

时间戳方法:

//获取当前时间戳
+(NSString *)getNowTimeTimestamp{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString;
}

三.在调用相册的地方引用方法

[AliyunUpload uploadImage:headImageArray FileDirectory:ENT_fileItemImageBody success:^(NSString *obj) {
            _pictureStr =obj ;//就是上传后的名称
            dispatch_sync(dispatch_get_main_queue(), ^{
            });
        }];

最后:奉献上我的demo(https://github.com/dt8888/TestView),有不足的地方,随时指教。

相关文章

网友评论

    本文标题:iOS 将图片(单张或多张)上传至阿里云详解

    本文链接:https://www.haomeiwen.com/subject/xsdesftx.html