上传图片文件至阿里云
首先cocoapod安装AliyunOSSiOS
一.请求阿里
//阿里云服务的sts认证请求
-
(void)getAliSts {
// 参数字典(服务器后台定义)
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) {
//服务器返回阿里相关配置信息
/
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) {
}];
}
二.由服务器返回数据配置阿里上传相关上传配置
//传图片给阿里
-
(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];
// 网络请求遇到异常失败后的重试次数
conf.maxRetryCount = 3;
// 网络请求的超时时间
conf.timeoutIntervalForRequest =30;
// 允许资源传输的最长时间
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); //上传头像至服务器 [self uploadImage:self.imagePathStr]; } else { NSLog(@" upload object failed, error: %@" , task.error); } return nil;
}];
}
三.将文件名地址传给后台服务器
//上传头像地址至服务器
-
(void)uploadImage:(NSString)imgStr {
// 参数字典
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(@"上传头像地址至服务器--------------");
MineInfoModel *info = [MineInfoModel mj_objectWithKeyValues:respondDic[@"result"]];
self.infoModel.aboutme = info.aboutme;
[self.tableView reloadData];} else { }
} errorCallbackFunction:^(NSError *error) {
}];
}
//获取图片路径名,服务器后台自己定制规则,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;
}