#ifndef HTTPWINDOW_H
#define HTTPWINDOW_H
#include <QProgressDialog>
#include <QNetworkAccessManager>
#include <QUrl>
#include "QFile"
class HttpPNG_Process : public QObject
{
Q_OBJECT
public:
explicit HttpPNG_Process(QObject *parent = Q_NULLPTR);
void startRequest(const QUrl &requestedUrl);
private slots:
void cancelDownload();
void httpFinished();
void httpReadyRead();
private:
QFile *openFileForWrite(const QString &fileName);
QUrl url;
QNetworkAccessManager q_QNetworkAccessManager_get;
QNetworkReply *reply_get;
QFile *file;
bool httpRequestAborted;
QNetworkAccessManager q_QNetworkAccessManager_post;
QNetworkReply *reply_post;
QUrl url_post;
public slots:
bool HttpGetPNG(QString dir,QString file_name);
bool HttpPostPNG(QString file_path);
};
#endif
#include <QtWidgets>
#include <QtNetwork>
#include <QUrl>
#include "HttpPNG_Process.h"
#include "ui_authenticationdialog.h"
HttpPNG_Process::HttpPNG_Process(QObject *parent)
: QObject(parent)
, reply_get(Q_NULLPTR)
, file(Q_NULLPTR)
, reply_post(Q_NULLPTR)
, httpRequestAborted(false)
{
HttpGetPNG("c:/data","1111111.png");
}
bool HttpPNG_Process::HttpPostPNG(QString file_path)
{
QFile* file = new QFile(file_path);
file->open(QIODevice::ReadOnly);
QHttpMultiPart *multi_part = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart image_part;
image_part.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
image_part.setHeader(QNetworkRequest::ContentDispositionHeader
,QVariant(QString("form-data; name=\"file\";filename=\"testfile.jpg\";")));
image_part.setBodyDevice(file);
multi_part->append(image_part);
reply_post = q_QNetworkAccessManager_post.post(QNetworkRequest(url_post), multi_part);
}
bool HttpPNG_Process::HttpGetPNG(QString dir,QString file_name)
{
QString file_path;
file_path=file_name;
const QString urlSpec="http://www.myip.cn/"+file_path;//URL如何定义
const QUrl newUrl=QUrl::fromUserInput(urlSpec);
QString downloadDir=QDir::cleanPath(dir.trimmed());
if (!downloadDir.isEmpty() && QFileInfo(downloadDir).isDir())
file_path.prepend(downloadDir + '/');
if (QFile::exists(file_path))
{
QFile::remove(file_path);
}
if (!newUrl.isValid())
{
return false;
}
file = openFileForWrite(file_path);
if (!file)
{
return false;
}
startRequest(newUrl);
}
调用下面两个函数实现Post和Get功能:
bool HttpGetPNG(QString dir,QString file_name);
bool HttpPostPNG(QString file_path);