本篇介绍Qt调用aws-sdk-cpp的window版本,包括创建桶,获取桶列表,上传,下载文件,删除文件,删除桶功能。
开发环境:Window11, Qt5.15.2, VS2022
源程序如下:
pro文件
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
INCLUDEPATH += ../include
CONFIG += c++17
DESTDIR = ../bin
#LIBS += -L$$PWD/libs/win64/lib -lminiolib
LIBS += -L../bin -laws-cpp-sdk-core
LIBS += -L../bin -laws-cpp-sdk-s3
LIBS += -L../bin -laws-cpp-sdk-transfer
message($$OUT_PWD)
# F:/qtexample/minioqt/build/Desktop_Qt_5_15_2_MSVC2019_64bit-Release/minioTest
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h \
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void initMinIO();
void createBucket();
void getBucketTest();
void uploadTest();
void downloadTest();
void deleteFile();
void deleteBucket();
public slots:
void slotAWSSDK();
void slotCreateBucket();
void slotGetBucket();
void slotUpload();
void slotDownload();
void slotDeleteFile();
void slotDeleteBucket();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <string.h>
#include <QDateTime>
#include <iostream>
#include <fstream>
#include <QFile>
#include <aws/core/Aws.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/DeleteObjectRequest.h>
#include <aws/s3/model/CreateBucketRequest.h>
#include <aws/s3/model/DeleteBucketRequest.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
using namespace std;
using namespace Aws::S3;
using namespace Aws::S3::Model;
#define PRINTTIME (QDateTime::currentDateTime().toString("hh:mm:ss.zzz"))
//#pragma comment(lib, "ws2_32.lib")
//#pragma comment(lib, "miniolib.lib")
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->btn_aws_sdk, SIGNAL(clicked()), this, SLOT(slotAWSSDK()));
connect(ui->btnCreateBucket, SIGNAL(clicked()), this, SLOT(slotCreateBucket()));
connect(ui->btnGetBucket, SIGNAL(clicked()), this, SLOT(slotGetBucket()));
connect(ui->btnUpload, SIGNAL(clicked()), this, SLOT(slotUpload()));
connect(ui->btnDownload, SIGNAL(clicked()), this, SLOT(slotDownload()));
connect(ui->btnDeleteFile, SIGNAL(clicked()), this, SLOT(slotDeleteFile()));
connect(ui->btnDeleteBucket, SIGNAL(clicked()), this, SLOT(slotDeleteBucket()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initMinIO()
{
// 连接服务器
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
Aws::InitAPI(options);
Aws::Client::ClientConfiguration cfg;
cfg.endpointOverride = "play.min.io";//官方测试服务器
cfg.scheme = Aws::Http::Scheme::HTTPS;
//cfg.verifySSL = false;
Aws::Auth::AWSCredentials cred("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
qDebug() << "initMinIO============1===============line========" << __LINE__;
Aws::S3::S3Client client(cred, cfg, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Always, false,
Aws::S3::US_EAST_1_REGIONAL_ENDPOINT_OPTION::NOT_SET);
std::string fileName = "test.txt";
fileName = "miniotest.zip";
fileName = "aaa.zip";
fileName = "abc.pdb";
fileName = "awsTest.pdb";
fileName = "test2.txt";
fileName = "StudyPEx64.exe";
std::string BucketName = "awsbucket";
qDebug() << "initMinIO============2================line========" << __LINE__;
// 创建Bucket
Aws::S3::Model::CreateBucketRequest create_bucket_request;
create_bucket_request.SetBucket(BucketName);
create_bucket_request.SetCreateBucketConfiguration({});
auto create_bucket_outcome = client.CreateBucket(create_bucket_request);
qDebug() << "initMinIO===========3=================line========" << __LINE__;
if (create_bucket_outcome.IsSuccess()) {
qDebug() << "Bucket created successfully.";
} else {
qDebug() << "Failed to create bucket: " <<
create_bucket_outcome.GetError().GetMessage().c_str();
Aws::ShutdownAPI(options);
return;
}
// 列出Buckets的名字
auto response = client.ListBuckets();
if (response.IsSuccess()) {
auto buckets = response.GetResult().GetBuckets();
for (auto iter = buckets.begin(); iter != buckets.end(); ++iter) {
qDebug() << "--" << iter->GetName().c_str()
<< iter->GetCreationDate().ToLocalTimeString(Aws::Utils::DateFormat::ISO_8601).c_str();
}
}
// 上传文件
QFile file(QString::fromStdString(fileName));
file.open(QIODevice::ReadOnly);
Aws::S3::Model::PutObjectRequest putObjectRequest;
putObjectRequest.WithBucket(BucketName.c_str()).WithKey(fileName.c_str());
std::shared_ptr<Aws::IOStream> input_data = Aws::MakeShared<Aws::StringStream>("PutObjectInputStream");
*input_data << file.readAll().toStdString();
file.close();
putObjectRequest.SetBody(input_data);
auto putObjectResult = client.PutObject(putObjectRequest);
if (putObjectResult.IsSuccess())
{
qDebug() << "upload file success!";
}
else
{
qDebug() << "upload file error: " <<
putObjectResult.GetError().GetExceptionName().c_str() << " " <<
putObjectResult.GetError().GetMessage().c_str();
Aws::ShutdownAPI(options);
return;
}
// 下载文件
Aws::S3::Model::GetObjectRequest object_request;
object_request.WithBucket(BucketName.c_str()).WithKey(fileName.c_str());
auto get_object_outcome = client.GetObject(object_request);
if (get_object_outcome.IsSuccess())
{
Aws::IOStream &local_file = get_object_outcome.GetResult().GetBody();
if (!local_file) {
qDebug() << "Error opening file";
Aws::ShutdownAPI(options);
return;
}
std::istreambuf_iterator<char> begin(local_file);
std::istreambuf_iterator<char> end;
std::string buffer(begin, end); // 读取整个文件内容
QFile file_(QString::fromStdString("./download_"+fileName));
if(file_.open(QIODevice::ReadWrite | QIODevice::Truncate)){
file_.write(QByteArray::fromStdString(buffer));
file_.close();
qDebug() << "download success!";
}
else
{
qDebug() << "download faild!";
}
}
else
{
std::cout << "GetObject error: " <<
get_object_outcome.GetError().GetExceptionName() << " " <<
get_object_outcome.GetError().GetMessage() << std::endl;
}
// 删除文件
Aws::S3::Model::DeleteObjectRequest delete_object_request;
delete_object_request.WithBucket(BucketName.c_str()).WithKey(fileName.c_str());
auto delete_object_outcome = client.DeleteObject(delete_object_request);
if (delete_object_outcome.IsSuccess()) {
qDebug() << "File deleted successfully.";
} else {
qDebug() << "Failed to delete file: " <<
delete_object_outcome.GetError().GetMessage().c_str();
}
// 删除Bucket,一定要先删除文件,再删除Bucket
Aws::S3::Model::DeleteBucketRequest delete_bucket_request;
delete_bucket_request.SetBucket(BucketName.c_str());
auto delete_bucket_outcome = client.DeleteBucket(delete_bucket_request);
if (delete_bucket_outcome.IsSuccess()) {
qDebug() << "Bucket deleted successfully.";
} else {
qDebug() << "Failed to delete bucket: " <<
delete_bucket_outcome.GetError().GetMessage().c_str();
}
Aws::ShutdownAPI(options);
}
void MainWindow::createBucket()
{
// 连接服务器
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
Aws::InitAPI(options);
Aws::Client::ClientConfiguration cfg;
cfg.endpointOverride = "play.min.io";//官方测试服务器
cfg.scheme = Aws::Http::Scheme::HTTPS;
//cfg.verifySSL = false;
Aws::Auth::AWSCredentials cred("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
qDebug() << "createBucket============1===============line========" << __LINE__;
Aws::S3::S3Client client(cred, cfg, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Always, false,
Aws::S3::US_EAST_1_REGIONAL_ENDPOINT_OPTION::NOT_SET);
std::string BucketName = "awsbucket";
qDebug() << "createBucket============2================line========" << __LINE__;
// 创建Bucket
Aws::S3::Model::CreateBucketRequest create_bucket_request;
create_bucket_request.SetBucket(BucketName);
create_bucket_request.SetCreateBucketConfiguration({});
auto create_bucket_outcome = client.CreateBucket(create_bucket_request);
qDebug() << "createBucket===========3=================line========" << __LINE__;
if (create_bucket_outcome.IsSuccess()) {
qDebug() << "Bucket created successfully.";
} else {
qDebug() << "Failed to create bucket: " <<
create_bucket_outcome.GetError().GetMessage().c_str();
Aws::ShutdownAPI(options);
return;
}
Aws::ShutdownAPI(options);
}
void MainWindow::getBucketTest()
{
// 初始化
qDebug() << "getBucketTest===========1===========" << PRINTTIME;
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
Aws::InitAPI(options);
qDebug() << "getBucketTest===========2===========" << PRINTTIME;
Aws::Client::ClientConfiguration cfg;
cfg.endpointOverride = "play.min.io";//官方测试服务器
cfg.scheme = Aws::Http::Scheme::HTTPS; //https协议
//cfg.verifySSL = false;
qDebug() << "getBucketTest==========3============" << PRINTTIME;
Aws::Auth::AWSCredentials cred("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
qDebug() << "getBucketTest==========4============" << PRINTTIME;
Aws::S3::S3Client client(cred, cfg, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Always, false,
Aws::S3::US_EAST_1_REGIONAL_ENDPOINT_OPTION::NOT_SET);
qDebug() << "getBucketTest==========5============" << PRINTTIME;
auto response = client.ListBuckets();
qDebug() << "getBucketTest==========6============" << PRINTTIME;
if (response.IsSuccess()) {
auto buckets = response.GetResult().GetBuckets();
for (auto iter = buckets.begin(); iter != buckets.end(); ++iter) {
cout << iter->GetName() << "\t" << iter->GetCreationDate().ToLocalTimeString(Aws::Utils::DateFormat::ISO_8601) << endl;
}
}
qDebug() << "getBucketTest==========7============" << PRINTTIME;
Aws::ShutdownAPI(options);
}
void MainWindow::uploadTest()
{
// 连接服务器
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
Aws::InitAPI(options);
qDebug() << "uploadTest============1===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::Client::ClientConfiguration cfg;
cfg.endpointOverride = "play.min.io";//官方测试服务器
cfg.scheme = Aws::Http::Scheme::HTTPS;
//cfg.verifySSL = false;
Aws::Auth::AWSCredentials cred("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
qDebug() << "uploadTest============2===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::S3::S3Client client(cred, cfg, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Always, false,
Aws::S3::US_EAST_1_REGIONAL_ENDPOINT_OPTION::NOT_SET);
std::string fileName = "test.txt";
fileName = "miniotest.zip";
fileName = "aaa.zip";
fileName = "abc.pdb";
fileName = "awsTest.pdb";
fileName = "test2.txt";
fileName = "awss3.dll";
fileName = "aws_sdk.log";
std::string BucketName = "mybucket";
BucketName = "awsbucket";
// 上传文件
//QFile file(QString::fromStdString(fileName));
//file.open(QIODevice::ReadOnly);
Aws::S3::Model::PutObjectRequest putObjectRequest;
putObjectRequest.WithBucket(BucketName.c_str()).WithKey(fileName.c_str());
//std::shared_ptr<Aws::IOStream> input_data = Aws::MakeShared<Aws::StringStream>("PutObjectInputStream");
//*input_data << file.readAll().toStdString();
//file.close();
//putObjectRequest.SetBody(input_data);
//https://developer.qiniu.com/kodo/12554/aws-sdk-cpp-examples
//Aws::S3::Model::PutObjectRequest putObjectRequest;
//putObjectRequest.SetBucket("<Bucket>");
//putObjectRequest.SetKey("<Key>");
std::shared_ptr<Aws::IOStream> requestBody = Aws::MakeShared<Aws::FStream>("PutObjectAllocationTag", fileName.c_str(), std::ios_base::in | std::ios_base::binary);
if (!*requestBody)
{
std::cerr << "Error: open file: " << strerror(errno) << std::endl;
qDebug() << "Error: open file:=====" << fileName.c_str();
return;
}
putObjectRequest.SetBody(requestBody);
qDebug() << "uploadTest============3===============line========" << __LINE__ << " time:" << PRINTTIME;
auto putObjectResult = client.PutObject(putObjectRequest);
if (putObjectResult.IsSuccess())
{
qDebug() << "upload file success!";
}
else
{
qDebug() << "upload file error: " <<
putObjectResult.GetError().GetExceptionName().c_str() << " " <<
putObjectResult.GetError().GetMessage().c_str();
Aws::ShutdownAPI(options);
return;
}
qDebug() << "uploadTest============4===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::ShutdownAPI(options);
}
void MainWindow::downloadTest()
{
// 连接服务器
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
Aws::InitAPI(options);
Aws::Client::ClientConfiguration cfg;
cfg.endpointOverride = "play.min.io";//官方测试服务器
cfg.scheme = Aws::Http::Scheme::HTTPS;
//cfg.verifySSL = false;
Aws::Auth::AWSCredentials cred("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
qDebug() << "initMinIO============1===============line========" << __LINE__;
Aws::S3::S3Client client(cred, cfg, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Always, false,
Aws::S3::US_EAST_1_REGIONAL_ENDPOINT_OPTION::NOT_SET);
std::string fileName = "test.txt";
fileName = "miniotest.zip";
fileName = "aaa.zip";
fileName = "abc.pdb";
fileName = "awsTest.pdb";
fileName = "test2.txt";
std::string BucketName = "mybucket";
qDebug() << "initMinIO============2================line========" << __LINE__;
// 下载文件
std::string downloadFileName = "./download_"+fileName;
Aws::S3::Model::GetObjectRequest object_request;
object_request.WithBucket(BucketName.c_str()).WithKey(fileName.c_str());
//object_request.WithBucket(BucketName.c_str()).WithKey(objectKey.c_str());
auto get_object_outcome = client.GetObject(object_request);
if (get_object_outcome.IsSuccess())
{
Aws::OFStream local_file;
local_file.open(downloadFileName.c_str(), std::ios::out | std::ios::binary);
local_file << get_object_outcome.GetResult().GetBody().rdbuf();
std::cout << "download success!==========================" << local_file.is_open() << std::endl;
}
else
{
std::cout << "GetObject error: " <<
get_object_outcome.GetError().GetExceptionName() << " " <<
get_object_outcome.GetError().GetMessage() << std::endl;
}
// QFile版
// Aws::S3::Model::GetObjectRequest object_request;
// object_request.WithBucket(BucketName.c_str()).WithKey(fileName.c_str());
// auto get_object_outcome = client.GetObject(object_request);
// if (get_object_outcome.IsSuccess())
// {
// Aws::IOStream &local_file = get_object_outcome.GetResult().GetBody();
// if (!local_file) {
// qDebug() << "Error opening file";
// Aws::ShutdownAPI(options);
// return;
// }
// std::istreambuf_iterator<char> begin(local_file);
// std::istreambuf_iterator<char> end;
// std::string buffer(begin, end); // 读取整个文件内容
// QFile file_(QString::fromStdString("./download_"+fileName));
// if(file_.open(QIODevice::ReadWrite | QIODevice::Truncate)){
// file_.write(QByteArray::fromStdString(buffer));
// file_.close();
// qDebug() << "download success!";
// }
// else
// {
// qDebug() << "download faild!";
// }
// }
// else
// {
// std::cout << "GetObject error: " <<
// get_object_outcome.GetError().GetExceptionName() << " " <<
// get_object_outcome.GetError().GetMessage() << std::endl;
// }
Aws::ShutdownAPI(options);
}
void MainWindow::deleteFile()
{
// 连接服务器
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
Aws::InitAPI(options);
qDebug() << "deleteFile============1===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::Client::ClientConfiguration cfg;
cfg.endpointOverride = "play.min.io";//官方测试服务器
cfg.scheme = Aws::Http::Scheme::HTTPS;
//cfg.verifySSL = false;
Aws::Auth::AWSCredentials cred("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
qDebug() << "deleteFile============2===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::S3::S3Client client(cred, cfg, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Always, false,
Aws::S3::US_EAST_1_REGIONAL_ENDPOINT_OPTION::NOT_SET);
std::string fileName = "test.txt";
fileName = "miniotest.zip";
fileName = "aaa.zip";
fileName = "abc.pdb";
fileName = "awsTest.pdb";
fileName = "test2.txt";
fileName = "awss3.dll";
fileName = "aws_sdk.log";
std::string BucketName = "mybucket";
BucketName = "awsbucket";
qDebug() << "deleteFile============4===============line========" << __LINE__ << " time:" << PRINTTIME;
// 删除文件
Aws::S3::Model::DeleteObjectRequest delete_object_request;
delete_object_request.WithBucket(BucketName.c_str()).WithKey(fileName.c_str());
auto delete_object_outcome = client.DeleteObject(delete_object_request);
if (delete_object_outcome.IsSuccess()) {
qDebug() << "File deleted successfully.";
} else {
qDebug() << "Failed to delete file: " <<
delete_object_outcome.GetError().GetMessage().c_str();
}
qDebug() << "deleteFile============3===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::ShutdownAPI(options);
}
void MainWindow::deleteBucket()
{
// 连接服务器
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
Aws::InitAPI(options);
qDebug() << "deleteBucket============1===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::Client::ClientConfiguration cfg;
cfg.endpointOverride = "play.min.io";//官方测试服务器
cfg.scheme = Aws::Http::Scheme::HTTPS;
//cfg.verifySSL = false;
Aws::Auth::AWSCredentials cred("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
qDebug() << "deleteBucket============2===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::S3::S3Client client(cred, cfg, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Always, false,
Aws::S3::US_EAST_1_REGIONAL_ENDPOINT_OPTION::NOT_SET);
std::string fileName = "test.txt";
fileName = "miniotest.zip";
fileName = "aaa.zip";
fileName = "abc.pdb";
fileName = "awsTest.pdb";
fileName = "test2.txt";
fileName = "awss3.dll";
fileName = "aws_sdk.log";
std::string BucketName = "mybucket";
BucketName = "awsbucket";
// 删除Bucket,一定要先删除文件,再删除Bucket
Aws::S3::Model::DeleteBucketRequest delete_bucket_request;
delete_bucket_request.SetBucket(BucketName.c_str());
auto delete_bucket_outcome = client.DeleteBucket(delete_bucket_request);
if (delete_bucket_outcome.IsSuccess()) {
qDebug() << "Bucket deleted successfully.";
} else {
qDebug() << "Failed to delete bucket: " <<
delete_bucket_outcome.GetError().GetMessage().c_str();
}
qDebug() << "deleteBucket============3===============line========" << __LINE__ << " time:" << PRINTTIME;
Aws::ShutdownAPI(options);
}
void MainWindow::slotCreateBucket()
{
qDebug() << "MainWindow::slotCreateBucket=========================";
createBucket();
}
void MainWindow::slotGetBucket()
{
qDebug() << "MainWindow::slotGetBucket=========================";
getBucketTest();
}
void MainWindow::slotUpload()
{
qDebug() << "MainWindow::slotUpload=========================";
uploadTest();
}
void MainWindow::slotDownload()
{
qDebug() << "MainWindow::slotDownload=========================";
downloadTest();
}
void MainWindow::slotDeleteFile()
{
qDebug() << "MainWindow::slotDeleteFile=========================";
deleteFile();
}
void MainWindow::slotDeleteBucket()
{
qDebug() << "MainWindow::slotDeleteBucket=========================";
deleteBucket();
}
void MainWindow::slotAWSSDK()
{
qDebug() << "MainWindow::slotAWSSDK=========================";
initMinIO();
}
界面:
参考:
Windows下Qt使用AWS SDK for C++连接MinIO服务器-CSDN博客
AWS SDK for C++_使用指南_对象存储 - 七牛开发者中心
GitHub - aws/aws-sdk-cpp: AWS SDK for C++
GitHub - minio/minio-cpp: MinIO C++ Client SDK for Amazon S3 Compatible Cloud Storage
AWS SDK for C++ - Developer Guide