美文网首页
阿里云 云存储

阿里云 云存储

作者: goyohol | 来源:发表于2017-09-29 07:35 被阅读77次
Aliyun

PCH文件:
/** 阿里云 */
#import <AliyunOSSiOS/OSSService.h>  //头文件
#define Ali_EndPoint_URL @"http://oss-cn-shanghai.aliyuncs.com" //URL
#define Ali_AccessKeyId @"abcdefg12345abcd"                     //AccessKeyId
#define Ali_AccessKeySecret @"abcdefg12345abcdefg12345ab"       //secretKeyId
#define Ali_SecurityToken @""                                   //securityToken
#define Ali_bucketName @"cuteKids-img"          //文件夹(路径)
#define Ali_objectKey @""



#define User_Def [NSUserDefaults standardUserDefaults]  //NSUserdefault


示例:图片存储处理

[1].图片上传

//选择图片,并上传
[BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
    
    if (image) { //图片已经挑选好

        //上传图片
        [SVProgressHUD showWithStatus:@"图片上传中..."];
        
        NSData * iconData = UIImagePNGRepresentation(image);//图片转为NSData类型
        
        NSString *endpoint = Ali_EndPoint_URL;//阿里云URL
        // 移动端建议使用STS方式初始化OSSClient。更多鉴权模式请参考后面的访问控制章节。
        id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken];
        OSSClientConfiguration * conf = [OSSClientConfiguration new];
        conf.maxRetryCount = 3; // 网络请求遇到异常失败后的重试次数
        conf.timeoutIntervalForRequest = 30; // 网络请求的超时时间
        conf.timeoutIntervalForResource = 24 * 60 * 60; // 允许资源传输的最长时间
        
        OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
        
        OSSPutObjectRequest * put = [OSSPutObjectRequest new];//PUT方式
        put.bucketName = Ali_bucketName;//路径
        NSDateFormatter * format = [[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyyMMddHHmmsss"];
        NSString * timeStr = [format stringFromDate:[NSDate date] ];
        NSString * mobileStr = [User_Def objectForKey:USER_MobileNumber]?[User_Def objectForKey:USER_MobileNumber]:@"";
        NSString * objKeyStr = [NSString stringWithFormat:@"%@-%@.png",mobileStr,timeStr];
        put.objectKey = objKeyStr; //图片存储名:“手机号-日期.png”
        put.uploadingData = iconData; //直接上传NSData
        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            //NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
            //显示进度:百分比
            [SVProgressHUD showProgress:(float)totalByteSent/(float)totalBytesExpectedToSend];
        };
        
        OSSTask * putTask = [client putObject:put];
        [putTask continueWithBlock:^id(OSSTask *task) {
            NSLog(@"%@",task);
            if (!task.error) {
                NSLog(@"upload object success!");
                
                [User_Def setObject:objKeyStr forKey:ICON_Avatar];
                [SVProgressHUD showSuccessWithStatus:@"图片上传成功"];

                //主线程:更换当前图片
                dispatch_async(dispatch_get_main_queue(), ^{ 
                      _iconImgV.image = image; 
                });
            } else {
                NSLog(@"upload object failed, error: %@" , task.error);
                
                [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
            }
            return nil;
        }];
        
        //[putTask waitUntilFinished];//可以等待任务完成
    }
}];






[2].获取云服务器存储地址:

//获取URL
NSString * publicURL = nil;

     
NSString *endpoint = Ali_EndPoint_URL;
// 移动端建议使用STS方式初始化OSSClient。更多鉴权模式请参考后面的访问控制章节。
id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken];
OSSClientConfiguration * conf = [OSSClientConfiguration new];
conf.maxRetryCount = 3; // 网络请求遇到异常失败后的重试次数
conf.timeoutIntervalForRequest = 30; // 网络请求的超时时间
conf.timeoutIntervalForResource = 24 * 60 * 60; // 允许资源传输的最长时间
        
OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
        
OSSPutObjectRequest * get = [OSSPutObjectRequest new];//get方式
get.bucketName = Ali_bucketName;//路径
NSString * objKeyStr = [NSString stringWithFormat:@"%@/avatar",[NSData data] ];
//get.objectKey = @"<objectKey>";//填写文件的路径
get.objectKey = @"18308080808-201706281539328.png";//图片存储名:“手机号-日期.png”
OSSTask * task = [client putObject:get];
task = [client presignPublicURLWithBucketName:Ali_bucketName
                                withObjectKey:get.objectKey];
if (!task.error) {
     publicURL = task.result;//获取到的URL
 } else {
      NSLog(@"sign url error: %@", task.error);
}

获取到的阿里云存储地址http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/18308080808-201706281539328.png


之后就可以定义一个URL的(固定):
#define GetAliDataHeaderUrl @"http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/" //外网(图片)




[3].使用地址:
<3-1>.融云聊天界面,头像配置

网络请求成功后,配置 融云头像地址:userInfo.portraitUri = publicURL;

//融云:个人信息配置
if ([responseObject[@"Code"] integerValue] == 0) { //网络请求成功
    
    for (NSDictionary * dict in responseObject[@"DataList"]) {

        //设置用户个人信息
        RCUserInfo * userInfo = [[RCUserInfo alloc] init];
        userInfo.userId = dict[@"userId"];        //1.用户id
        userInfo.name = dict[@"userName"];        //2.用户名
        NSString * picUrlStr;  //头像地址
        if (dict[@"icon"]) {
            //阿里云图片URL
            picUrlStr = [NSString stringWithFormat:@"%@%@",GetAliDataHeaderUrl,dict[@"icon"] ];
        } else { //网络占位(默认)图片
            picUrlStr = @"http://img.qq1234.org/uploads/allimg/140520/3_140520152454_6.jpg";
        }
        userInfo.portraitUri = picUrlStr;         //3.头像地址
        
        //融云【方式二】:统一配置
        //RCUserInfo * userInfo = [[RCUserInfo alloc] initWithUserId:dict[@"userId"] name:dict[@"userName"] portrait:picUrlStr];
        

        [[RCIM sharedRCIM] setCurrentUserInfo:userInfo];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.conversationMessageCollectionView reloadData];
    });
}



//头像存储URL:
//#define GetAliDataHeaderUrl @"http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/"  //外网(图片)



<3-2>.一般图像的使用: SDWebImage加载

NSString * picUrlStr = [NSString stringWithFormat:@"%@%@",GetAliDataHeaderUrl,model.createrAvatar];
[_iconImgV sd_setImageWithURL:[NSURL URLWithString:picUrlStr] placeholderImage:[UIImage imageNamed:@"userIcon"]]






服务器 数据管理

基础配置:

NSString *endpoint = Ali_EndPoint_URL;
// 移动端建议使用STS方式初始化OSSClient。更多鉴权模式请参考后面的访问控制章节。
id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken];
OSSClientConfiguration * conf = [OSSClientConfiguration new];
conf.maxRetryCount = 3; // 网络请求遇到异常失败后的重试次数
conf.timeoutIntervalForRequest = 30; // 网络请求的超时时间
conf.timeoutIntervalForResource = 24 * 60 * 60; // 允许资源传输的最长时间

OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];



[1].查看所有Object:

//查看所有Object
OSSGetBucketRequest * getBucket = [OSSGetBucketRequest new];
getBucket.bucketName = Ali_bucketName;
// 可选参数,具体含义参考:https://docs.aliyun.com/#/pub/oss/api-reference/bucket&GetBucket
// getBucket.marker = @"";
// getBucket.prefix = @"";
// getBucket.delimiter = @"";
OSSTask * getBucketTask = [client getBucket:getBucket];
[getBucketTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        OSSGetBucketResult * result = task.result;
        NSLog(@"get bucket success!");
        for (NSDictionary * objectInfo in result.contents) {
            NSLog(@"list object: %@", objectInfo);
        }
    } else {
        NSLog(@"get bucket failed, error: %@", task.error);
    }
    return nil;
}];


[2].检查文件是否存在

NSString * objKeyStr = @"18308080808-201706281539328.png";
//检查文件是否存在
NSError * error = nil;
BOOL isExist = [client doesObjectExistInBucket:Ali_bucketName objectKey:objKeyStr error:&error];
if (!error) {
    if(isExist) {
        NSLog(@"File exists.");
    } else {
        NSLog(@"File not exists.");
    }
} else {
    NSLog(@"Error!");
}


[3].删除Object

NSString * deleteObjKeyStr = @"18308080808-201706281539328.png";
//删除Object
OSSDeleteObjectRequest * delete = [OSSDeleteObjectRequest new];
delete.bucketName = Ali_bucketName;
delete.objectKey = deleteObjKeyStr;
OSSTask * deleteTask = [client deleteObject:delete];
[deleteTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        // ...
        //只显示文字
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = @"删除成功!";
        hud.margin = 10.f;
        hud.offset = CGPointMake(0, 0.f);
        hud.removeFromSuperViewOnHide = YES;
        [hud hideAnimated:YES afterDelay:1.5f];
    }
    return nil;
}];
// [deleteTask waitUntilFinished];



其实数据管理这一步,处理小文件(小图片,小文档)是不太需要的;但处理大文件(音乐、视频)还是必要的!

我个人建议:处理!(不要因为别人跟你说不用处理,就不去处理!)
这多多少少是一个程序员的素质逻辑缜密性的体现!😂😂😂😂😂😂😂😂










goyohol's essay

相关文章

网友评论

      本文标题:阿里云 云存储

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