通过 Qt 来实现来上传文件相对麻烦一点,参考Qt 官方简单例子总结了一下,可以直接使用。
相关模块
- QNetworkAccessManager 发起 GET/POST 请求
- QNetworkReply 描述响应信息
- QHttpMultiPart 模拟表单域
- QNetworkRequest 构建请求地址等信息
实例部分代码
1、h文件部分代码
private:
void uploadControlParameterDownloadFile();
QFile *controlParameterDownloadFile;
QNetworkReply *uploadControlParameterDownloadFileReply;
public slots:
void httpUploadControlParameterDownloadFileFinished();
2、cpp文件部分代码
void DataAnalysis::uploadControlParameterDownloadFile()
{
// 传输文件:电机控制配置参数
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QString path = QString("resources/net/control_parameter_download_1.ini");
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("ini"));
controlParameterDownloadFile = new QFile(path);
QFileInfo info(controlParameterDownloadFile->fileName());
uint timeT = QDateTime::currentDateTime().toTime_t();
QString fileNewName =
QString("%1@%2_%3.%4").arg(DeviceSystem::instance()->getPrintControl()->getPrintUuid()).arg(timeT).arg(info.baseName()).arg(info.suffix());
QLOG_INFO() << "uploadParameterFile fileNewName == " << fileNewName << endl;
QString contentDispositionHeader = QString("form-data; name=\"file\"; filename=\"%1\"").arg(fileNewName);
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(contentDispositionHeader));
controlParameterDownloadFile->open(QIODevice::ReadOnly);
imagePart.setBodyDevice(controlParameterDownloadFile);
controlParameterDownloadFile->setParent(multiPart);
multiPart->append(imagePart);
QUrl url(DATA_ANALYSIS_URL_INI_FILE_UPLOAD);
QNetworkRequest request(url);
QNetworkAccessManager m_httpNAM;
uploadControlParameterDownloadFileReply = m_httpNAM.post(request, multiPart);
multiPart->setParent(uploadControlParameterDownloadFileReply);
connect(uploadControlParameterDownloadFileReply, SIGNAL(finished()), this, SLOT(httpUploadControlParameterDownloadFileFinished()));
QEventLoop eventLoop;
connect(&m_httpNAM, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));
eventLoop.exec();
}
void DataAnalysis::httpUploadControlParameterDownloadFileFinished()
{
if (uploadControlParameterDownloadFileReply->error() == QNetworkReply::NoError)
{
QLOG_INFO() << "upload file finished";
controlParameterDownloadFile->flush();
controlParameterDownloadFile->close();
uploadControlParameterDownloadFileReply->deleteLater();
uploadControlParameterDownloadFileReply = nullptr;
delete controlParameterDownloadFile;
controlParameterDownloadFile = nullptr;
}
else
{
QLOG_ERROR() << "error string:" << uploadControlParameterDownloadFileReply->errorString();
uploadControlParameterDownloadFileReply->deleteLater();
}
}
感谢大家的阅读,更多精彩等待下次创作,你最大的支持就是:赞同+评论+赞赏+...,关注我。
另外,也欢迎大家关注我的个人公众号 “聊者说”。
网友评论