转载请注明出处:http://www.cnblogs.com/dachen408/p/8185060.html
qt5 上传图片到http服务器,亲测可以用,qt5.8+vs2015,直接上码;
头文件:
#ifndef UPDATEPICTEST_H #define UPDATEPICTEST_H #include <QtWidgets/QMainWindow> #include "ui_updatepictest.h" #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QHttpMultiPart> #include <QFile> #include <QDataStream> #include <QTextCodec> class UpdatePicTest : public QMainWindow { Q_OBJECT public: UpdatePicTest(QWidget *parent = 0); ~UpdatePicTest(); private slots: void slot_requestFinished(); void on_pushButton_clicked(); void upLoadError(QNetworkReply::NetworkError code); void uploadProcess(qint64 bytesReceived, qint64 bytesTotal); private: QNetworkAccessManager * m_pNetWorkManager = NULL; void testUpload(); QNetworkReply *reply; private: Ui::UpdatePicTestClass ui; }; #endif // UPDATEPICTEST_H
cpp,
http://ip:port改为对应的服务器和端口号
#include "updatepictest.h" #include <QDebug> UpdatePicTest::UpdatePicTest(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); m_pNetWorkManager = new QNetworkAccessManager(); } UpdatePicTest::~UpdatePicTest() { } void UpdatePicTest::slot_requestFinished() { QByteArray resultContent = reply->readAll(); QTextCodec* pCodec = QTextCodec::codecForName("UTF-8"); QString strResult = pCodec->toUnicode(resultContent); int nHttpCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();//http返回码 ui.textEdit->setPlainText(strResult); ui.edt_code->setText(QString("%1").arg(nHttpCode)); } void UpdatePicTest::on_pushButton_clicked() { testUpload(); } void UpdatePicTest::upLoadError(QNetworkReply::NetworkError code) { qDebug() << code; } void UpdatePicTest::uploadProcess(qint64 bytesReceived, qint64 bytesTotal) { qDebug() << bytesReceived << bytesTotal; } void UpdatePicTest::testUpload() { QString path = ui.lineEdit->text().trimmed(); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png")); imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"%1\"; filename=\"%2\"").arg("offline.png").arg(path)); QFile *file = new QFile(path); file->open(QIODevice::ReadOnly); imagePart.setBodyDevice(file); imagePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(imagePart); QNetworkRequest request(QUrl("http://ip:port")); reply = m_pNetWorkManager->post(request, multiPart); multiPart->setParent(reply); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(upLoadError(QNetworkReply::NetworkError))); connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(uploadProcess(qint64, qint64))); connect(reply, SIGNAL(finished()), this, SLOT(slot_requestFinished())); }