ali OSS 上传

+ (instancetype)manager {

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

_instance = [[self alloc] init];

});

return _instance;

}

- (instancetype)init {

if (self = [super init]) {

[self getDownloadItems];

[self initOSSClient];

if(!self.allUplaodReceipts) self.allUplaodReceipts = [NSMutableDictionary dictionary];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveUploadItems) name:kYCUploadSessionSaveUploadStatus object:nil];

}

return self;

}

简单上传

- (OSSPutObject *)uploadReceiptForModel:(DiskCloudDiskModel *)model withCell:(MyDiskFileCell *)cell IndexPath:(NSIndexPath *)indexPath{

if (model.urlOutputPath == nil) return nil;

DiskCloudDiskModel * oldModel = self.allUplaodReceipts[[NSString stringWithFormat:@"%@",model.Oid]];

OSSPutObject *receipt = oldModel.putObject;

if (receipt && oldModel.isShowPress) return receipt;

receipt = [OSSPutObject new];

model.putObject = receipt;

receipt.bucketName = bucketNames;

receipt.objectKey = [NSString stringWithFormat:@"%@%@",[HSInstance shareInstance].userInfo.SessionID,[NSString timeStampAtNow]];

NSLog(@"%@",receipt.objectKey);

receipt.uploadingFileURL = model.urlOutputPath;

receipt.contentType = @"";

receipt.contentMd5 = @"";

receipt.contentEncoding = @"";

receipt.contentDisposition = @"";

AaronUploadItem * item = [AaronUploadItem new];

receipt.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {

NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);

CGFloat progress = (CGFloat)totalByteSent/totalBytesExpectedToSend;

dispatch_async(dispatch_get_main_queue(), ^{

model.passValue = progress;

cell.progress = progress;

});

};

OSSTask *putTask = [clients putObject:receipt];

[putTask continueWithBlock:^id(OSSTask *task) {

if (!task.error) {

model.isShowPress = NO;

model.isUpload = NO;

[item uploadReceiptForcomplete];

if ([self.delegate respondsToSelector:@selector(uploadItemStatusChanged:)]) {

[self.delegate uploadItemStatusChanged:model];

}

NSLog(@"upload object success!");

} else {

NSLog(@"upload object failed, error: %@" , task.error);

}

return nil;

}];

[self.allUplaodReceipts setObject:model forKey:[NSString stringWithFormat:@"%@",model.Oid]];

[self saveUploadItems];

return receipt;

}

// 断点续传

- (void)resumableUploadModel:(DiskCloudDiskModel *)model withCell:(MyDiskFileCell *)cell IndexPath:(NSIndexPath *)indexPath {

__block NSString * recordKey;

//    NSString * docDir = [self getDocumentDirectory];

//    NSString * filePath = [docDir stringByAppendingPathComponent:@"file10m"];

NSString * bucketName = bucketNames;

NSString * objectKey = [NSString stringWithFormat:@"%@%@",[HSInstance shareInstance].userInfo.SessionID,[NSString timeStampAtNow]];

[[[[[[OSSTask taskWithResult:nil] continueWithBlock:^id(OSSTask *task) {

// 为该文件构造一个唯一的记录键

NSURL * fileURL = model.urlOutputPath;

NSDate * lastModified;

NSError * error;

[fileURL getResourceValue:&lastModified forKey:NSURLContentModificationDateKey error:&error];

if (error) {

return [OSSTask taskWithError:error];

}

recordKey = [NSString stringWithFormat:@"%@-%@-%@-%@", bucketName, objectKey, [OSSUtil getRelativePath:model.urlOutputPath.absoluteString], lastModified];

// 通过记录键查看本地是否保存有未完成的UploadId

NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

return [OSSTask taskWithResult:[userDefault objectForKey:recordKey]];

}] continueWithSuccessBlock:^id(OSSTask *task) {

if (!task.result) {

// 如果本地尚无记录,调用初始化UploadId接口获取

OSSInitMultipartUploadRequest * initMultipart = [OSSInitMultipartUploadRequest new];

initMultipart.bucketName = bucketName;

initMultipart.objectKey = objectKey;

initMultipart.contentType = @"application/octet-stream";

return [clients multipartUploadInit:initMultipart];

}

OSSLogVerbose(@"An resumable task for uploadid: %@", task.result);

return task;

}] continueWithSuccessBlock:^id(OSSTask *task) {

NSString * uploadId = nil;

if (task.error) {

return task;

}

if ([task.result isKindOfClass:[OSSInitMultipartUploadResult class]]) {

uploadId = ((OSSInitMultipartUploadResult *)task.result).uploadId;

} else {

uploadId = task.result;

}

if (!uploadId) {

return [OSSTask taskWithError:[NSError errorWithDomain:OSSClientErrorDomain

code:OSSClientErrorCodeNilUploadid

userInfo:@{OSSErrorMessageTOKEN: @"Can't get an upload id"}]];

}

// 将“记录键:UploadId”持久化到本地存储

NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

[userDefault setObject:uploadId forKey:recordKey];

[userDefault synchronize];

return [OSSTask taskWithResult:uploadId];

}] continueWithSuccessBlock:^id(OSSTask *task) {

// 持有UploadId上传文件

OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];

resumableUpload.bucketName = bucketName;

resumableUpload.objectKey = objectKey;

resumableUpload.uploadId = task.result;

model.resumableUpload = resumableUpload;

resumableUpload.uploadingFileURL = model.urlOutputPath;

resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {

NSLog(@"%lld %lld %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);

CGFloat progress = (CGFloat)totalBytesSent/totalBytesExpectedToSend;

dispatch_async(dispatch_get_main_queue(), ^{

model.passValue = progress;

cell.progress = progress;

});

};

return [clients resumableUpload:resumableUpload];

}] continueWithBlock:^id(OSSTask *task) {

if (task.error) {

if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {

// 如果续传失败且无法恢复,需要删除本地记录的UploadId,然后重启任务

[[NSUserDefaults standardUserDefaults] removeObjectForKey:recordKey];

}

} else {

NSLog(@"upload completed!");

// 上传成功,删除本地保存的UploadId

[[NSUserDefaults standardUserDefaults] removeObjectForKey:recordKey];

}

return nil;

}];

}


#pragma mark- OSS Method/* STS */

- (void)initOSSClient { 

 idcredential2 = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {

OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];

NSString * urlString = [BASE_URL(loginToken) stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

[dict setValue:@"c432626a-1754-4874-8c1d-2fa4356188a8" forKey:@"SessionID"];

//   设置 指示器 无蒙板效果

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

manager.requestSerializer = [AFJSONRequestSerializer serializer];

manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager.requestSerializer setValue:@"c432626a-1754-4874-8c1d-2fa4356188a8" forHTTPHeaderField:@"SessionID"];

[manager POST:urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

NSLog(@"OSSTaskCompletionSource responseObject = %@",responseObject);

self.responseObject = responseObject[@"token"];

[tcs setResult:responseObject];

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

NSLog(@"%@",error);

if (error) {

[tcs setError:error];

return;

}

}];

//同步

[tcs.task waitUntilFinished];

if (tcs.task.error) {

NSLog(@"get token error: %@", tcs.task.error);

return nil;

}

else {

//获取token返回的参数

OSSFederationToken * token = [OSSFederationToken new];

NSDictionary * dict = self.responseObject[@"Credentials"];

token.tAccessKey = [dict objectForKey:@"AccessKeyId"];

token.tSecretKey = [dict objectForKey:@"AccessKeySecret"];

token.tToken = [dict objectForKey:@"SecurityToken"];

token.expirationTimeInGMTFormat = [dict objectForKey:@"Expiration"];

NSLog(@"get token: %@", token);

return token;

}

}];

OSSClientConfiguration * conf = [OSSClientConfiguration new];

conf.maxRetryCount = 1;

conf.maxConcurrentRequestCount = 1;

conf.timeoutIntervalForRequest = 30;

conf.timeoutIntervalForResource = 24 * 60 * 60;

clients = [[OSSClient alloc] initWithEndpoint:endPoints credentialProvider:credential2 clientConfiguration:conf];

}

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