阿里云多图上传

来说说阿里云的上传功能,最开始是想要自己封装一下OSSClient,类似于单例类的存在,折腾了两三天,也没有解决这个问题,原因在于 异步请求,block回调,等各种的不同步,因为自己太菜了,这一块后面再多看看资料 学习一下。。。

阿里云的官方文档上很清楚的,比较坑的是 我们的NSURLRequest直接请求,拿不到token的数据,因为需要网页先行登录才可以。

最后调整为对接口进行封装,似乎采用这种方式的比较多,使用获得的STS令牌 再去向阿里云上传图片。

多图上传

```

+ (void)upLoadImagesToAliyun:(NSArray *)imagesArr imageNames:(NSArray *)imageNames  completionBlock:(void(^)(NSMutableArray *errorIndexs,UploadImageState state))completeBlock{

[HHHomeData requestAliyunSTSInfoBlock:^(HHAliyunSTSModel *STSModel, NSString *errorStr) {

dispatch_queue_t uploadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_t uploadGroup = dispatch_group_create();

//异步上传所有图片

__block NSMutableArray *errorIndexs = [NSMutableArray array];

for (int i = 0; i < imagesArr.count; i++) {

dispatch_group_async(uploadGroup, uploadQueue, ^{

UIImage *image = imagesArr[i];

NSString *imageName = imageNames[i];

//上传图片的二进制数据

OSSPutObjectRequest *put = [OSSPutObjectRequest new];

put.bucketName = STSModel.bucket;

//                put.objectKey = [NSString stringWithFormat:@"%@%@",STSModel.objectKeyPrefix,imageName];

put.objectKey = imageName;

HHLog(@"bucket:%@====上传时的objectKey==%@",put.bucketName,put.objectKey);

put.uploadingData = [image getImageDataWithCompress];

put.contentType = @"image/jpeg";

put.contentMd5 = [OSSUtil base64Md5ForData:put.uploadingData];

//                HHLog(@"data===%lu",(unsigned long)put.uploadingData.length);

OSSClient *client = [self getClientWithAccessKeyId:STSModel.accessKeyId secrectKey:STSModel.accessKeySecret token:STSModel.securityToken];

//                HHLog(@"==id=%@,secrec>>%@",STSModel.accessKeyId,STSModel.accessKeySecret);

OSSTask *putTask = [client putObject:put];

//                putTask = [client presignPublicURLWithBucketName:STSModel.bucket withObjectKey:put.objectKey];

put.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent, int64_t totalBytesExpectedToSend) {

HHLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);

if (totalByteSent == [[image getImageDataWithCompress] length]) {

}

};

[putTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {

if (!task.error) {

HHLog(@"第%d张上传成功",i);

}else{

HHLog(@"第%d张上传失败,error==>%@",i,task.error.localizedDescription);

[errorIndexs addObject:@(i)];

}

return nil;

}];

[putTask waitUntilFinished];

});

}

dispatch_group_notify(uploadGroup, uploadQueue, ^{

HHLog(@"上传结束后的通知");

if (errorIndexs.count == 0) {

if (completeBlock) {

completeBlock(nil,UploadImageSuccess);

}

}else{

if (completeBlock) {

completeBlock(errorIndexs,UploadImageFailed);

}

}

});

}];

}

```

你可能感兴趣的:(阿里云多图上传)