最近 需要搞一个阿里云的文件上传 手机端主要做了图片上传
pod安装:pod 'AliyunOSSiOS', '~> 2.5.2'
主要就是需要四个参数:accessKey secretKey endpoint bucket
这四个参数都是在网页生成的 另外在 页面 创建accessKey secretKey 的时候换需要短信验证码 真心麻烦
集成过程中 主要是要选好endpoint (其中内网 外网是不一样的 第一次弄得时候在这上面搞了半天 原来endpoint弄错了)
最后生成的图片url由endpoint+bucket(+文件夹名字(如果有的话))+你自己命名的图片名字 构成的
上代码
NSString * const AccessKey = @"XXXXXXXXXXXXX";
NSString * const SecretKey = @"XXXXXXXXXXXXX";
NSString * const endPoint = @"XXXXXXXXXXXXX";
NSString * const bucketName = @"XXXXXXXXXXXXX"; static NSString *imageTemp = @"imgTemp"; -------------------------------------------------------------------------------------------
- (void)initOSSClient
{ id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey
secretKey:SecretKey]; // 自实现签名,可以用本地签名也可以远程加签
// id<OSSCredentialProvider> credential1 = [[OSSCustomSignerCredentialProvider alloc] initWithImplementedSigner:^NSString *(NSString *contentToSign, NSError *__autoreleasing *error) {
// NSString *signature = [OSSUtil calBase64Sha1WithData:contentToSign withSecret:@"<your secret key>"];
// if (signature != nil) {
// *error = nil;
// } else {
// // construct error object
// *error = [NSError errorWithDomain:@"<your error domain>" code:OSSClientErrorCodeSignFailed userInfo:nil];
// return nil;
// }
// return [NSString stringWithFormat:@"OSS %@:%@", @"<your access key>", signature];
// }]; // Federation鉴权,建议通过访问远程业务服务器获取签名
// 假设访问业务服务器的获取token服务时,返回的数据格式如下:
// {"accessKeyId":"STS.iA645eTOXEqP3cg3VeHf",
// "accessKeySecret":"rV3VQrpFQ4BsyHSAvi5NVLpPIVffDJv4LojUBZCf",
// "expiration":"2015-11-03T09:52:59Z[;",
// "federatedUser":"335450541522398178:alice-001",
// "requestId":"C0E01B94-332E-4582-87F9-B857C807EE52",
// "securityToken":"CAES7QIIARKAAZPlqaN9ILiQZPS+JDkS/GSZN45RLx4YS/p3OgaUC+oJl3XSlbJ7StKpQp1Q3KtZVCeAKAYY6HYSFOa6rU0bltFXAPyW+jvlijGKLezJs0AcIvP5a4ki6yHWovkbPYNnFSOhOmCGMmXKIkhrRSHMGYJRj8AIUvICAbDhzryeNHvUGhhTVFMuaUE2NDVlVE9YRXFQM2NnM1ZlSGYiEjMzNTQ1MDU0MTUyMjM5ODE3OCoJYWxpY2UtMDAxMOG/g7v6KToGUnNhTUQ1QloKATEaVQoFQWxsb3cSHwoMQWN0aW9uRXF1YWxzEgZBY3Rpb24aBwoFb3NzOioSKwoOUmVzb3VyY2VFcXVhbHMSCFJlc291cmNlGg8KDWFjczpvc3M6KjoqOipKEDEwNzI2MDc4NDc4NjM4ODhSAFoPQXNzdW1lZFJvbGVVc2VyYABqEjMzNTQ1MDU0MTUyMjM5ODE3OHIHeHljLTAwMQ=="}
/*
id<OSSCredentialProvider> credential2 = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
NSURL * url = [NSURL URLWithString:@"http://localhost:8080/distribute-token.json"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
[tcs setError:error];
return;
}
[tcs setResult:data];
}];
[sessionTask resume];
[tcs.task waitUntilFinished];
if (tcs.task.error) {
NSLog(@"get token error: %@", tcs.task.error);
return nil;
} else {
NSDictionary * object = [NSJSONSerialization JSONObjectWithData:tcs.task.result
options:kNilOptions
error:nil];
OSSFederationToken * token = [OSSFederationToken new];
token.tAccessKey = [object objectForKey:@"accessKeyId"];
token.tSecretKey = [object objectForKey:@"accessKeySecret"];
token.tToken = [object objectForKey:@"securityToken"];
token.expirationTimeInGMTFormat = [object objectForKey:@"expiration"];
NSLog(@"get token: %@", token);
return token;
}
}];
*/ OSSClientConfiguration * conf = [OSSClientConfiguration new];
conf.maxRetryCount = 2;
conf.timeoutIntervalForRequest = 30;
conf.timeoutIntervalForResource = 24 * 60 * 60; client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
}
// 异步上传
- (void)uploadObjectAsync
{
OSSPutObjectRequest * put = [OSSPutObjectRequest new]; // required fields
put.bucketName = bucketName; NSString *imageName = [imageTemp stringByAppendingPathComponent:[[NSUUID UUID].UUIDString stringByAppendingString:@".jpg"]];
put.objectKey = @"testImage.jpg";
UIImage *image = [UIImage imageNamed:@"test.jpg"];
NSData *data = UIImageJPEGRepresentation(image, 0.3);
put.uploadingData = data; // put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
// NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
// }; put.contentType = @"";
put.contentMd5 = @"";
put.contentEncoding = @"";
put.contentDisposition = @""; OSSTask * putTask = [client putObject:put]; [putTask continueWithBlock:^id(OSSTask *task) {
NSLog(@"objectKey: %@", put.objectKey);
if (!task.error) {
NSLog(@"upload object success!");
} else {
NSLog(@"upload object failed, error: %@" , task.error);
}
return nil;
}];
}