直接上代码:
第一种方法:
QUrl url;
url.setUrl(makeFullUrl(m_opt.submitdebateresult.url));
#if QT_VERSION >= 0x050000
QUrlQuery q;
addSessionIdQueryItem(&q);
q.addQueryItem(m_opt.submitdebateresult.query.mediaId, param.mediaId());
q.addQueryItem(m_opt.submitdebateresult.query.exerciseId, param.exerciseId());
url.setQuery(q);
#else
addSessionIdQueryItem(&url);
url.addQueryItem(m_opt.submitdebateresult.query.mediaId, param.mediaId());
url.addQueryItem(m_opt.submitdebateresult.query.exerciseId, param.exerciseId());
#endif
QNetworkRequest request;
request.setUrl(url);
//这里两个分支分别代码QT5及以主和QT4.8 的的url加参数的方法。
request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/octet-stream"));
// 上面这句,是代码以二进制流的方式post数据。
<span style="font-size:14px;background-color: rgb(255, 255, 255);"><strong> QFile file(filePath); // 这里是你自己的文件路径
file.open(QIODevice::ReadOnly);
int file_len = file.size();
QDataStream in(&file);
m_buf = new char[file_len];
in.readRawData( m_buf, file_len);
file.close();</strong></span>
QByteArray dataArray = QByteArray(m_buf, fileLength);
m_netReply = m_networkAccessManager->post(request , dataArray);
connect(m_netReply, SIGNAL(uploadProgress ( qint64 ,qint64 )), this, SLOT( slotUploadProgress(qint64 ,qint64)));
connect(m_netReply, SIGNAL(finished()), this, SLOT(slotUploadFinished()));
第二种方法:
比第一种简单,但效率没第一种高,只写主要代码。
QFile file(filePath);
file.open(QIODevice::ReadOnly);
data = file.readAll();
file.close();
m_netReply = m_networkAccessManager->post (request, "file="+data.toBase64 ()+"");
// 这里是把文件转成base64的,好处是,防止文件传的过程因为符号,空格的原因,导致文件数据失真。
connect(m_netReply, SIGNAL(uploadProgress ( qint64 ,qint64 )), this, SLOT( slotUploadProgress(qint64 ,qint64)));
connect(m_netReply, SIGNAL(finished()), this, SLOT(slotUploadFinished()));