- 导入SDK,这部分就不介绍了
- 这里只介绍如果上传图片
阿里云的官方文档讲解的比较详细,但是坑爹的是少了行代码,所以找不到错误就很难受了
//将image转成Data
NSData *data = UIImageJPEGRepresentation(image, 0);
NSString *endpoint = model.point;//后台传回来的
//AccessKeyId --- secretKeyId 都是后台返回的 securityToken填空字符串就好了
id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:model.AccessKeyId secretKeyId:model.AccessKeySecret securityToken:@""];
OSSClient*client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
OSSPutObjectRequest * put = [OSSPutObjectRequest new];
put.bucketName = model.ducketName;//后台返回的
//根据用户ID和时间戳来生成一段字符串 来保证图片的唯一性
NSString *timestr = [NSString stringWithFormat:@"%@%@",[UserDefaultTool userId],[self obtainNowTimeStr]];
//将后台返回的uploadFilePath和上面的字符串拼接在一起
put.objectKey = [NSString stringWithFormat:@"%@%@.jpg",model.uploadFilePath,timestr];
put.uploadingData = data; // 直接上传NSData
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:model.ducketName
withObjectKey:[NSString stringWithFormat:@"%@%@.jpg",model.uploadFilePath,timestr]];
if (!task.error) {
//上传成功了,把图片URL地址传出去 task.result就是图片URL 传给自己服务器就好了
if (updataBackResult) {
updataBackResult(task.result);
}
} else {
NSLog(@"upload object failed, error: %@" , task.error);
}
return nil;
}];