QtHttp文件上传到服务器
文件上传到服务器在Qt客户端开发的过程中,比较常见。简单封装了一下,复制下来头文件声明一下,就可以直接使用了。
一般来说,不会就单单上传一个文件,前面会带着几个普通字段。代码中,我用FileID做了一个例子。
//包含的头文件混了,自行分辨一下
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QEventLoop>
#include <QHttpPart>
//直接复制过去,在头文件里面声明一下就能用
bool HttpPostFileUpload(const QString p_sUploadDirPath/*文件路径*/, QString &p_sReturnData/*返回数据*/)
{
//网络请求对象
QNetworkRequest request;
//网络请求地址
QString sRequestUrl = "www.xxxx.xx";
request.setUrl(QUrl(sRequestUrl));
// 发送的数据
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
// 普通字段
QHttpPart FileID;
FileID.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"001\""));
FileID.setBody(QString("xxxx").toLatin1());
multiPart->append(FileID);
// 文件
QFileInfo fileInfo(p_sUploadDirPath);
QFile *pFile = new QFile(p_sUploadDirPath);
if(!pFile->open(QIODevice::ReadOnly))
{
qDebug() << "文件" + p_sUploadDirPath + "打开失败";
}
pFile->setParent(multiPart); //给pFile设置parent,pFile就不需要再delete了
QHttpPart filePart;
filePart.setBodyDevice(pFile);
filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
QString requestFormat = QString::fromUtf8("form-data;name=%1;filename=%2;")
.arg("file")
.arg(fileInfo.fileName());
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(requestFormat));
multiPart->append(filePart);
// 网络请求
QNetworkAccessManager *accessManager = new QNetworkAccessManager();
QNetworkReply *reply = accessManager->post(request, multiPart);
multiPart->setParent(reply); // multiPart不需要delete了
//事件循环
QEventLoop eventLoop;
QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
// 获取返回的数据
p_sReturnData = QString(reply->readAll());
qDebug() << "返回参数:" << p_sReturnData ;
pFile->close();
reply->abort();
accessManager->deleteLater();//不主动释放会在卸载DLL时造成耗时
accessManager=NULL;
return true;
}