OSS上传文件

阿里云OSS上传文件,我这是用的老版本的获取OSSClient的方式,因为我们后台没有做OSS的接入,现在新版本的需要后台接入OSS

NSString *endpoint = @"https://oss-cn-hangzhou.aliyuncs.com";

// 移动端建议使用STS方式初始化OSSClient。
id credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * _Nullable{
    OSSFederationToken *token = [OSSFederationToken new];
    // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
    token.tAccessKey = @"AccessKeyId";
    token.tSecretKey = @"AccessKeySecret";
    // 从STS服务获取的安全令牌(SecurityToken)。
    token.tToken = @"SecurityToken";
    // 临时访问凭证的过期时间。
    token.expirationTimeInGMTFormat = @"Expiration";
    return token;
}];

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

这里的token是需要后台返回的,而且每一次上传文件都需要调用一次后台返回再调用上传的OSS接口,我觉得太麻烦了,还是用的以前的版本的初始化方式,但是其实这种方式是不太安全的,需要安全的话还是用新版本的方式会比较好

OSSManager.h

//
//  OSSManager.h
//  QingLa
//
//  Created by 苏永耀 on 2021/12/10.
//

#import 
#import 

typedef void(^OSSResultBlock)(NSString * _Nullable fileURL);

static NSString * const endpoint = @"http://oss-cn-beijing.aliyuncs.com/";
static NSString * const FileURLHeader = @"http://qingweilaikeji.oss-cn-beijing.aliyuncs.com/";
static NSString * const AccessKeySecret = @"AccessKeySecret";
static NSString * const AccessKeyID = @"AccessKeyId";
static NSString * const BucketName = @"qingweilaikeji";

//文件在服务器的路径
static NSString * const AvatarURL = @"iOS/Avatar";

static NSString * const CoverURL = @"iOS/Cover";

static NSString * const OtherURL = @"iOS/Other";

typedef enum : NSUInteger {
    OSSTypeAvatar,
    OSSTypeCover,
    OSSTypeOther,
} OSSType;

NS_ASSUME_NONNULL_BEGIN

@interface OSSManager : NSObject

@property (nonatomic,strong) OSSNetworkingUploadProgressBlock progressBlock;
@property (nonatomic,strong) OSSResultBlock resultBlock;
+(instancetype)manager;

-(void)uploadImageWithType:(OSSType)type image:(UIImage *)image resultBlock:(OSSResultBlock)resultBlock;

@end

NS_ASSUME_NONNULL_END

OSSManager.m

//
//  OSSManager.m
//  QingLa
//
//  Created by 苏永耀 on 2021/12/10.
//

#import "OSSManager.h"
@interface OSSManager ()
{
    OSSClient *client;
}
@end
@implementation OSSManager

static OSSManager *_manager;
+ (instancetype)manager {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    
    return _manager;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    
    return _manager;
}
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
    return _manager;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        OSSPlainTextAKSKPairCredentialProvider *ossPlainTextAKSKCredentialProvider = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKeyID secretKey:AccessKeySecret];
        
        client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:ossPlainTextAKSKCredentialProvider];
    }
    return self;
}

-(void)uploadImageWithType:(OSSType)type image:(UIImage *)image resultBlock:(nonnull OSSResultBlock)resultBlock{
    
    [self showLoading];
    
    
    OSSPutObjectRequest *put = [[OSSPutObjectRequest alloc] init];
    put.bucketName = BucketName;
    
    put.objectKey = [self getPathWithType:type];
    
    NSLog(@"%@%@",FileURLHeader,put.objectKey);
    put.uploadingData = UIImageJPEGRepresentation(image, 0.5f);
    WeakSelf
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld   ,%lld   ,%lld",bytesSent,totalBytesSent,totalBytesExpectedToSend);
        if (weakSelf.progressBlock) {
            weakSelf.progressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend);
        }
    };
    
    OSSTask *task = [client putObject:put];
    [task continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideLoading];
            if (!task.error) {
                if (weakSelf.resultBlock) {
                    weakSelf.resultBlock([NSString stringWithFormat:@"%@%@",FileURLHeader,put.objectKey]);
                }
                resultBlock([NSString stringWithFormat:@"%@%@",FileURLHeader,put.objectKey]);
                NSLog(@"上传成功!!! %@",task.result);
            }else{
                
                NSLog(@"上传失败!!!");
                [self showMessage:@"上传失败"];
            }
        });
        
        
        return nil;
    }];
    [task waitUntilFinished];
    
    
}


-(NSString *)getPathWithType:(OSSType)type{
    
    NSString *path;
    NSTimeInterval now = [[NSDate new] timeIntervalSince1970];
    if (type == OSSTypeAvatar) {
        path = [NSString stringWithFormat:@"%@/%li_%f.png",AvatarURL,UserManager._id,now];
    }else if (type == OSSTypeCover){
        path = [NSString stringWithFormat:@"%@/%li_%f.png",CoverURL,UserManager._id,now];
    }else if (type == OSSTypeOther){
        path = [NSString stringWithFormat:@"%@/%li_%f.png",OtherURL,UserManager._id,now];
    }
    
    return path;
}


@end

你可能感兴趣的:(OSS上传文件)