阿里云oss图片上传

2017-07-28-阿里云oss图片上传



pod 'AliyunOSSiOS', '~> 2.1.2'



#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UploadManager : NSObject
+ (void)upload:(UIImage *)image;


@end



#import "UploadManager.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AliyunOSSiOS/OSSCompat.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonHMAC.h>

NSString * const AccessKey = @"LTAIxu2fm9BePjCN";
NSString * const SecretKey = @"IhWbSlgqi8Z0gdtOkzbjyMOm2SNQBy";
NSString * const endpoint = @"oss-cn-shanghai.aliyuncs.com"; // 阿里云地址
NSString * const bucketName = @"bestmath"; //相当于磁盘目录
NSString * const folder = @"h5"; //真正的文件目录,随意创建




@implementation UploadManager


+ (void)upload:(UIImage *)image
{
id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey
secretKey:SecretKey];
OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
OSSPutObjectRequest * put = [OSSPutObjectRequest new];

put.bucketName = bucketName;
NSString *objectKeys = [NSString stringWithFormat:@"h5/%@.jpg",[self getTimeNow]];

put.objectKey = objectKeys;
//put.uploadingFileURL = [NSURL fileURLWithPath:fullPath];

NSData *imageData = UIImageJPEGRepresentation(image, 0.1);

put.uploadingData = imageData;
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
OSSTask * putTask = [client putObject:put];

[putTask continueWithBlock:^id(OSSTask *task) {
task = [client presignPublicURLWithBucketName:bucketName
withObjectKey:objectKeys];
NSLog(@"objectKey: %@.%@/%@", bucketName,endpoint,put.objectKey); //图片地址
if (!task.error) {

NSLog(@"upload object success!");

} else {
NSLog(@"upload object failed, error: %@" , task.error);
}
return nil;
}];
}


+ (NSString *)getTimeNow
{
NSString* date;
NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
[formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
date = [formatter stringFromDate:[NSDate date]];
//取出个随机数
int last = arc4random() % 10000;
NSString *timeNow = [[NSString alloc] initWithFormat:@"%@-%i", date,last];
NSLog(@"%@", timeNow);
return timeNow;
}
















Loading Disqus comments...
Table of Contents