阿里云图片上传的基本思路:
1、选择图片
2、将图片保存在本地,同时返回图片路径、并生成缩略图用于 UI 显示。
3、上传图片,成功后将步骤 2 中的图片名传给服务器。
单张图片上传的例子官方的 demo 中已经有了,这里直接上多图上传。
具体实现是结合 NSOperationQueue,设置 operation 间的依赖来实现多图上传。
这里省略步骤 1、2 ,直接上传图片:
+ (void)uploadImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{
id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey secretKey:SecretKey];
OSSClient *client = [[OSSClient alloc] initWithEndpoint:AliYunHost credentialProvider:credential];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = images.count;
NSMutableArray *callBackNames = [NSMutableArray array];
int i = 0;
for (UIImage *image in images) {
if (image) {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
//任务执行
OSSPutObjectRequest * put = [OSSPutObjectRequest new];
put.bucketName = BucketName;
NSString *imageName = [kTempFolder stringByAppendingPathComponent:[[NSUUID UUID].UUIDString stringByAppendingString:@".jpg"]];
put.objectKey = imageName;
[callBackNames addObject:imageName];
NSData *data = UIImageJPEGRepresentation(image, 0.3);
put.uploadingData = data;
OSSTask * putTask = [client putObject:put];
[putTask waitUntilFinished]; // 阻塞直到上传完成
if (!putTask.error) {
NSLog(@"upload object success!");
} else {
NSLog(@"upload object failed, error: %@" , putTask.error);
}
if (isAsync) {
if (image == images.lastObject) {
NSLog(@"upload object finished!");
if (complete) {
complete([NSArray arrayWithArray:callBackNames] ,UploadImageSuccess);
}
}
}
}];
if (queue.operations.count != 0) {
[operation addDependency:queue.operations.lastObject];
}
[queue addOperation:operation];
}
i++;
}
if (!isAsync) {
[queue waitUntilAllOperationsAreFinished];
NSLog(@"haha");
if (complete) {
if (complete) {
complete([NSArray arrayWithArray:callBackNames], UploadImageSuccess);
}
}
}
}
Screen Shot 2016-05-31 at 10.09.02 PM.png
根据返回的地址可以 bucketName + aliYunHost + 地址 在浏览器中直接访问了。
例如 bucketName = "my-bucket"; aliYunHost = "http://oss-cn-shenzhen.aliyuncs.com/"; 返回图片地址 = "temp/69058506-679B-432C-AD11-61A34C067235.jpg";
那么可以通过 “my-bucket.oss-cn-shenzhen.aliyuncs.com/temp/69058506-679B-432C-AD11-61A34C067235.jpg” 直接在浏览器中进行访问
网友评论
"201707210256108050.png",
"201707210256106013.png"
) 但是连接里面打不开呢 网页打开NoSuchKey The specified key does not exist. 5971A44B23395DD72FCEEE57 bangli-upload01.oss-cn-shenzhen.aliyuncs.com 201707210250205513.png 是什么情况?
用你说的方式my-bucket.oss-cn-shenzhen.aliyuncs.com/temp/69058506-679B-432C-AD11-61A34C067235.jpg
访问我获取的内容,提示
AccessDenied You have no right to access this object because of bucket acl.
如果你使用浏览器上传文件,则浏览器会自动在header中设置正确地content type,然后对文件的访问会得到正确地回应。
如果采用编程的方式,处理文件上传,保持到 aliyun OSS中,则需要正确设置content type,否则,缺省的content type都为application/octet-stream。
如果类型是application/octst-stream,则在访问文件时,会导致下载操作。在浏览器中,会弹出下载保存的对话框
图片地址一般是你们后台返回的