最近由于公司上线了云平台,需要用Qt与云平台进行对接,故拾起了network模块。
众所周知Qt网络http相关的类QNetworkAccessManager发挥着举足轻重的作用。
普通的http:GET POST PUT DELETE已经耳熟能详,网上也有很多的文章有介绍到。
今天我要说的是平时不常用的上传文件,使用的是QHttpMultiPart模块:
QUrl url("http://xxx.xxxxxx.com/api/xxxxxx/xxxx/report");
QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
//form-data普通字符
QString a = "TextA";
QHttpPart aPart;
aPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"a\""));
aPart.setBody(a.toUtf8());
//form-data文件
QFile* file = new QFile("D:/xx.db");
QString fileName = QFileInfo(*file).fileName();
QString fileNaem_ = file->fileName();
QHttpPart filePart;
//warning 1
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\""+fileName+"\""));
//warning 2
filePart.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
if(file->open(QIODevice::ReadOnly)) {
filePart.setBodyDevice(file);
}
file->setParent(multiPart);
//form-data文件2
QString fileName1 = QFileInfo(*file1).fileName();
QString fileName1_ = file1->fileName();
QHttpPart filePart1;
//warning 1
filePart1.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"data\"; filename=\""+fileName1+"\""));
//warning 2
filePart1.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
if(file1->open(QIODevice::ReadOnly)) {
filePart1.setBodyDevice(file1);
}
file1->setParent(multiPart);
multiPart->append(aPart);
multiPart->append(filePart);
multiPart->append(filePart1);
QNetworkRequest request(url);
QString bdry = multiPart->boundary();
//warning 3
request.setHeader(QNetworkRequest::ContentTypeHeader,"multipart/form-data;boundary=" + bdry);
QNetworkReply *reply = manager->post(request, multiPart);
connect(reply, &QNetworkReply::uploadProgress, [=](qint64 bytesSent, qint64 bytesTotal)
{
if ((reply->error() == QNetworkReply::NoError) &&
(0 != bytesSent) && (0 != bytesTotal))
{
int uploadProgress = static_cast<int>(bytesSent * 100 / bytesTotal);
qDebug() << "###-->" << uploadProgress << endl;
}
});
代码中的warning1、warning2、warning3这三个地方需要注意,基本没什么问题。
如果有问题的话,可以先用postman测试,测试OK的话,同步使用Fiddler进行抓包查看一下具体发送的数据是什么:
Postman截图:
Fiddler截图:
然后再使用Qt发送命令,对比一下两者发送http请求数据的区别,这样可以快速找到问题所在,及时调整代码并测试。