最近工作中遇到需要将文件上传到阿里云的oss服务器上,所以根据阿里云的说明文档,封装了一个类,希望对大家有所帮助,如发现问题,欢迎批评指正~
主要功能:
(1)设置连接池数,设置请求超时时间,设置建立连接的超时时间
(2)进度条显示实时进度
(3)上传文件,下载文件到内存中和到本地路径下
alibabacloud_handle.h
#ifndef _ALIBABACLOUD_HANDLE_
#define _ALIBABACLOUD_HANDLE_
#include <string>
#include <stdio.h>
#include <alibabacloud/oss/OssClient.h>
#include <memory>
#include <fstream>
#include <iostream>
using namespace AlibabaCloud::OSS;
namespace ALIBABACLOUD_HANDLE{
class alibabacloud_handle{
public:
// desc: 构造函数用于初始化OSS账号信息以及初始化sdk
// param: 参数一/AccessKeyId 参数二/AccessKeySecret 参数三/Endpoint 参数四/BucketName
// return: NULL
alibabacloud_handle(const std::string &,const std::string &,const std::string &,const std::string &);
// desc: 关闭sdk
// param: NULL
// return: NULL
~alibabacloud_handle();
// desc: 上传文件
// param: 参数一/阿里云上的路径及要保存的文件名 参数二/本地路径
// return: 成功返回true,失败返回false
bool upload_files(const std::string &,const std::string &);
// desc: 查询阿里云某路径下的文件列表
// param: 参数一/阿里云上的路径
// return: 成功返回true,失败返回false
bool query_directory(const std::string &);
// desc: 下载文件到本地路径下
// param: 参数一/阿里云上的路径及要保存的文件名 参数二/本地路径
// return: 成功返回true,失败返回false
bool download_files(const std::string &,const std::string &);
// desc: 下载文件到内存中
// param: 参数一/阿里云上的路径及要保存的文件名 参数二/保存数据的字符串
// return: 成功返回true,失败返回false
bool download_files_to_memory(const std::string &,std::string &);
// desc: 进度条显示
// param: transfered/已完成的大小 total/总大小
// return: NULL
void ProgressCallback(size_t increment, int64_t transfered, int64_t total, void* userData) const;
public:
int status;
private:
//OSS 通过使用 AccessKeyId 和 AccessKeySecret 对称加密的方法来验证某个请求的发送者身份。AccessKeyId 用于标识用户;AccessKeySecret 是用户用于加密签名字符串和 OSS 用来验证签名字符串的密钥,必须保密。
std::string AccessKeyId;
std::string AccessKeySecret;
std::string Endpoint; //OSS对外服务的访问域名
std::string BucketName; //存储空间名
ClientConfiguration conf;
OssClient *oss_client;
TransferProgress progressCallback;
const char lable[5];
};
}
#endif
alibabacloud_handle.cpp
#include "alibabacloud_handle.h"
#include <unistd.h>
#include <string.h>
namespace ALIBABACLOUD_HANDLE{
alibabacloud_handle::alibabacloud_handle(const std::string &AccessKeyId,const std::string &AccessKeySecret,const std::string &Endpoint,const std::string &BucketName):AccessKeyId(AccessKeyId),AccessKeySecret(AccessKeySecret),Endpoint(Endpoint),BucketName(BucketName),lable({'|','/','-','\\','\\'})
{
InitializeSdk();
/* 设置连接池数,默认为16个 */
conf.maxConnections = 20;
/* 设置请求超时时间,超时没有收到数据就关闭连接,默认为10000ms */
conf.requestTimeoutMs = 8000;
/* 设置建立连接的超时时间,默认为5000ms */
conf.connectTimeoutMs = 8000;
oss_client = new OssClient(Endpoint, AccessKeyId, AccessKeySecret, conf);
if(oss_client == NULL){
status = -1;
return;
}else{
status = 1;
}
auto callback = std::bind(&alibabacloud_handle::ProgressCallback,this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
std::placeholders::_4
);
progressCallback = { callback , nullptr };
}
alibabacloud_handle::~alibabacloud_handle(){
ShutdownSdk();
}
bool alibabacloud_handle:: upload_files(const std::string &target_path, const std::string &local_path){
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(local_path.c_str(), std::ios::in|std::ios::binary);
PutObjectRequest request(BucketName, target_path, content);
request.setTransferProgress(progressCallback);
auto outcome = oss_client->PutObject(request);
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return false;
}
return true;
}
bool alibabacloud_handle::query_directory(const std::string &target_directory){
std::string nextMarker = "";
ListObjectsRequest request1(BucketName);
auto outcome = oss_client->ListObjects(request1);
do {
/* 列举文件 */
ListObjectsRequest request(BucketName);
/* 设置正斜线(/)为文件夹的分隔符 */
request.setDelimiter("/");
request.setPrefix(target_directory);
request.setMarker(nextMarker);
outcome = oss_client->ListObjects(request);
if (!outcome.isSuccess ()) {
/* 异常处理 */
std::cout << "ListObjects fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return false;
}
for (const auto& object : outcome.result().ObjectSummarys()) {
std::cout << "object"<<
",name:" << object.Key() <<
" ,size:" << object.Size() <<
" ,lastmodify time:" << object.LastModified() << std::endl;
}
for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
std::cout << "commonPrefix" << ",name:" << commonPrefix << std::endl;
}
nextMarker = outcome.result().NextMarker();
} while (outcome.result().IsTruncated());
return true;
}
bool alibabacloud_handle::download_files(const std::string &target_directory,const std::string &local_directory){
DownloadObjectRequest request(BucketName, target_directory, local_directory);
request.setTransferProgress(progressCallback);
auto outcome = oss_client->ResumableDownloadObject(request);
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "ResumableDownloadObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return false;
}else{
return true;
}
}
void alibabacloud_handle::ProgressCallback(size_t increment, int64_t transfered, int64_t total, void* userData) const
{
int i = (int)((transfered*1.0/total*1.0) *100);
printf("[%d%%][%c]\r", i , lable[i % 4]);
fflush(stdout);
}
bool alibabacloud_handle::download_files_to_memory(const std::string &target_directory,std::string &buf){
GetObjectRequest request(BucketName, target_directory);
request.setTransferProgress(progressCallback);
auto outcome = oss_client->GetObject(request);
if (outcome.isSuccess()) {
std::cout << "getObjectToBuffer" << " success, Content-Length:" << outcome.result().Metadata().ContentLength() << std::endl;
*(outcome.result().Content()) >> buf;
}
else {
/*异常处理*/
std::cout << "getObjectToBuffer fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return false;
}
return true;
}
}
main.cpp
#include "alibabacloud_handle.h"
int main(){
ALIBABACLOUD_HANDLE::alibabacloud_handle *p = new ALIBABACLOUD_HANDLE::alibabacloud_handle("xxx", "xxx", "http://oss-cn-shenzhen.aliyuncs.com", "xxx");
if(p->status == -1){
printf("alibabacloud_handle constructor error\n");
exit(-1);
}
//上传文件
p->upload_files("XXX/XXX/XXX", "XXX/XXX/XXX");
//查询文件夹中文件
p->query_directory("XXX/XXX/XXX");
//下载文件到本地路径
p->download_files("XXX/XXX/XXX","./XXX.txt");
//下载文件到本地内存
std::string p_buf;
p->download_files_to_memory("XXX/XXX/XXX",p_buf);
std::cout << p_buf << std::endl;
if (p != NULL)
{
delete p;
}
}
参考:
https://help.aliyun.com/document_detail/106556.html?spm=a2c4g.11186623.6.926.75cb4176w686Pc