首先cocoapod安裝AliyunOSSiOS
一.請(qǐng)求阿里
//阿里云服務(wù)的sts認(rèn)證請(qǐng)求
-
(void)getAliSts {
// 參數(shù)字典(服務(wù)器后臺(tái)定義)
NSMutableDictionary* dictParams = [NSMutableDictionary dictionaryWithCapacity:0];
[dictParams setObject:@"446b0752c174e319281db45a8696ecf7" forKey:@"API[app_key]"];
[dictParams setObject:@"json" forKey:@"API[output]"];
[dictParams setObject:@"816b81d40440f2e3a8e1acfde1f7334e" forKey:@"API[access_token]"];
[dictParams setObject:@"header" forKey:@"type"];
//urlString:接口地址
[NetworkTools requestWithMethod:GET urlString:@"http://wb.yunlala.com/bvb/alists/oss_put" parameters:dictParams callbackFunction:^(NSURLResponse *response, NSDictionary respondDic) {
//服務(wù)器返回阿里相關(guān)配置信息
/
2018-07-11 21:42:09.253987+0800 BWB[5459:3359590] {
"result" : {
"SecurityToken" : "CAIS8gF1q6Ft5B2yfSjIr4nEKIjNle5b0rKsZmPLjUwPQfZVgbzdsTz2IH9EenlhCeEWtPgylGxU7/cdlqpuFcYdpokHy2s0vPpt6gqET9frha7ctM496vCMHWyUFGS0vqv7aPn4S9XwY+qkb0u++AZ43br9c0fFPTmiKobbsYN7Sd4VUwKkF00kYu1bPQx/ssQXGGLMPPK2SH7Qj3HXEVBjt3gX6wo9y9zmkpLMsUCP3Q2mlLVN99moGPX+MZkwZqUYesyuwel7epDG1CNt8BVQ/M909vcbqWmX74HMUwMNvkXab7OFrccDKxRiP7jhwUKQCBo//hqAAQE0ly1dpxu54bSCp/4opXqW8I8MxFSByeyDrKbPsJ2CHMxAjRVSfPWDj7YCrA46Mm7SHhkdYdUhNlTRiTzBAJeNcNl9Ii7DTN2jhcegWNkKzY1b+vmmKHOlx0F+NM04NYlMmC0q1TC0tS2m5zsHpgYDBb+L8l+v7kUqILCKHYsd",
"BucketName" : "bweibo-header",
"Expiration" : "2018-07-11T14:42:09Z",
"AccessKeySecret" : "BYRANG885aScWN8oCFGp4HqE4C9Dok48HBNMBe4nWKSM",
"EndPoint" : "oss-cn-beijing.aliyuncs.com",
"AccessKeyId" : "STS.NJqc2yx1zepGdEziLZMyynyvS"
},
"code" : "200"
}
*/
if ([respondDic[@"code"] integerValue]==200) {
self.model = [MineAliOssModel mj_objectWithKeyValues:respondDic[@"result"]];
//上傳文件至阿里云
[self uploadToAli];
} else {}
} errorCallbackFunction:^(NSError *error) {
}];
}
二.由服務(wù)器返回?cái)?shù)據(jù)配置阿里上傳相關(guān)上傳配置
//傳圖片給阿里
-
(void)uploadToAli {
id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken *{
OSSFederationToken * token = [OSSFederationToken new];
token.tAccessKey = self.model.AccessKeyId;
token.tSecretKey = self.model.AccessKeySecret;
token.tToken = self.model.SecurityToken;
token.expirationTimeInGMTFormat = self.model.Expiration;return token;
}];
OSSClientConfiguration * conf = [OSSClientConfiguration new];
// 網(wǎng)絡(luò)請(qǐng)求遇到異常失敗后的重試次數(shù)
conf.maxRetryCount = 3;
// 網(wǎng)絡(luò)請(qǐng)求的超時(shí)時(shí)間
conf.timeoutIntervalForRequest =30;
// 允許資源傳輸?shù)淖铋L(zhǎng)時(shí)間
conf.timeoutIntervalForResource =24 * 60 * 60;
// 你的阿里地址前面通常是這種格式 :http://oss……
OSSClient *client = [[OSSClient alloc] initWithEndpoint:self.model.EndPoint credentialProvider:credential];
OSSPutObjectRequest *putRequest = [OSSPutObjectRequest new];
putRequest.bucketName = self.model.BucketName;
self.imagePathStr = [self getimagePathStr];//文件名,自定義
putRequest.objectKey = self.imagePathStr;
putRequest.uploadingData = UIImageJPEGRepresentation(self.imgOrg, 1); // 直接上傳NSData
putRequest.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent, int64_t totalBytesExpectedToSend) {NSLog(@" %lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
OSSTask *putTask = [client putObject:putRequest];
[putTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {NSLog(@" upload object success!"); OSSPutObjectResult * result = task.result; NSLog(@" result.requestId : %@",result.requestId); NSLog(@" result.httpResponseHeaderFields : %@",result.httpResponseHeaderFields); NSLog(@" result.eTag : %@",result.eTag); NSLog(@" result.serverReturnJsonString : %@",result.serverReturnJsonString); //上傳頭像至服務(wù)器 [self uploadImage:self.imagePathStr]; } else { NSLog(@" upload object failed, error: %@" , task.error); } return nil;
}];
}
三.將文件名地址傳給后臺(tái)服務(wù)器
//上傳頭像地址至服務(wù)器
-
(void)uploadImage:(NSString)imgStr {
// 參數(shù)字典
NSMutableDictionary dictParams = [NSMutableDictionary dictionaryWithCapacity:0];
[dictParams setObject:APP_KEY forKey:@"API[app_key]"];
[dictParams setObject:@"816b81d40440f2e3a8e1acfde1f7334e" forKey:@"API[access_token]"];
[dictParams setObject:@"json" forKey:@"API[output]"];
[dictParams setObject:@"oauth2" forKey:@"API[auth_type]"];
[dictParams setObject:@"user" forKey:@"mod"];
[dictParams setObject:@"edit" forKey:@"code"];
[dictParams setObject:imgStr forKey:@"header"];NSString* urlStr = [NSString stringWithFormat:@"%@/api.php", DomainName];
[NetworkTools requestWithMethod:POST urlString:urlStr parameters:dictParams callbackFunction:^(NSURLResponse *response, NSDictionary *respondDic) {
if ([respondDic[@"code"] integerValue]==200) {
NSLog(@"上傳頭像地址至服務(wù)器--------------");
MineInfoModel *info = [MineInfoModel mj_objectWithKeyValues:respondDic[@"result"]];
self.infoModel.aboutme = info.aboutme;
[self.tableView reloadData];} else { }
} errorCallbackFunction:^(NSError *error) {
}];
}
//獲取圖片路徑名,服務(wù)器后臺(tái)自己定制規(guī)則,md5路徑
- (NSString *)getimagePathStr {
NSData *imageData = UIImageJPEGRepresentation(self.imgOrg, 1);
NSString *name = [imageData md5String];
NSRange range;
range.location = 27;
range.length = 1;
NSString *str1 = [name substringWithRange:range];
range.location = 13;
range.length = 1;
NSString *str2 = [name substringWithRange:range];
range.location = 5;
range.length = 1;
NSString *str3 = [name substringWithRange:range];
range.location = 19;
range.length = 1;
NSString *str4 = [name substringWithRange:range];
NSString *path = [NSString stringWithFormat:@"%@%@/%@%@/%@.jpg",str1,str2,str3,str4,name];
return path;
}