QT 5.8 用QNetwork 上传图片到php服务器,并通过url下载图片

.h

#ifndef REMOVEBGCONN_H
#define REMOVEBGCONN_H

#include <QObject>
#include <QFile>
#include <QThread>
#include <QTimer>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QHttpMultiPart>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>

class QDownUpLoadImage : public QObject
{
    Q_OBJECT
public:
    QDownUpLoadImage();
	void solveReplyGet(QByteArray picRaw, QString filePath);
signals:
    void receivedData(QByteArray d, QString filePath);
    void connectError(QString e);
    void connectInfo(QString info);

public slots:
    void postData(QString filepath, QString token, bool start);
    bool postDataReal();
    void solveReply();
	void solveRecveImage();
    void clearData();
	void postImageData(QString filepath);
	void downImageUrl(QString url);
	void solveRecveDownImage(QNetworkReply* reply);
private:
	QNetworkAccessManager *accessManager;
    QNetworkReply* reply;
	
    QFile *file;
    std::vector<QString> filepath;
    std::vector<QString> token;
    int i = 0;
};

#endif // REMOVEBGCONN_H



.cpp

#include "Stdafx.h"
#include "QDownUpLoadImage.h"
#include<iostream>
#include <iphlpapi.h>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QSslConfiguration>
#include <QtNetwork/QSslSocket>
#include "json\json.h"


QDownUpLoadImage::QDownUpLoadImage()
{ 
	//SSL_library_init();
	//SSL_load_error_strings();
	
	 accessManager = new QNetworkAccessManager();

	 qDebug() << accessManager->supportedSchemes();
	// qDebug() << QSslSocket::sslLibraryBuildVersionString();
   // qDebug() << QSslSocket::supportsSsl() << QSslSocket::sslLibraryBuildVersionString() << QSslSocket::sslLibraryVersionString();
}


void QDownUpLoadImage::downImageUrl(QString url)
{
	disconnect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(solveRecveDownImage(QNetworkReply*)));
	connect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(solveRecveDownImage(QNetworkReply*)));
	accessManager->get(QNetworkRequest(QUrl(url)));

}



void QDownUpLoadImage::solveRecveDownImage(QNetworkReply* reply)
{
	QByteArray ba = reply->readAll();
	if (ba.size() > 100)
	{
		std::cout << "st";
		QImage* img2 = new QImage();
		img2->loadFromData(ba);

		if (img2->isNull())
			std::cout << "oops";

		if (img2->save("omg2.jpg", "JPG"))
		{
			std::cout << "saved";

			QFile File("omg2.png");
			File.open(QIODevice::WriteOnly);
			File.write(ba);
			File.close();
		}	
		else
			std::cout << "dont...";


	}
	
}


void  QDownUpLoadImage::postImageData(QString filepath)
{
	QFile file(filepath);
	if (!file.open(QIODevice::ReadOnly)) {
		qDebug() << "file open failed.";
		return;
	}
	QByteArray data = file.readAll();
	file.close();


	QString strRemoteUrl = "http://127.0.0.1/design/image.php";
	QNetworkRequest request;
	//? request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
	request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
	//QSslConfiguration config;
	// 发送https请求前准备工作;
	request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
	
	request.setUrl(QUrl(strRemoteUrl));
	reply = accessManager->post(request, "fileData=" + data.toBase64() + "&oldimagepath="+ filepath.toUtf8().toBase64());
	emit connectInfo("正在发送...");

	QObject::connect(reply, &QNetworkReply::finished, this, &QDownUpLoadImage::solveRecveImage);
	return ;

}

void QDownUpLoadImage::postData(QString filepath, QString token, bool start)
{
    this->filepath.push_back(filepath);
    this->token.push_back(token);
    if(start)
    {
        i = 0;
        postDataReal();
    }
}




void QDownUpLoadImage::solveReplyGet(QByteArray picRaw, QString filePath)
{
	bool isFileNotDir = false;
	QString outputPath = "GenRemoveBack";
	if (isFileNotDir)
	{
		QFileInfo fileinfo(outputPath);
		if (!fileinfo.dir().exists())
			if (!fileinfo.dir().mkdir(fileinfo.dir().absolutePath()))
			{
				//ui->plainTextEdit->appendPlainText(QString("创建路径失败:%1").arg(fileinfo.dir().absolutePath()));
				return;
			}
	}
	else
	{
		QDir dir(outputPath);
		if (!dir.exists())
			if (!dir.mkdir(dir.absolutePath()))
			{
				//ui->plainTextEdit->appendPlainText(QString("创建路径失败:%1").arg(dir.absolutePath()));
				return;
			}
		QFileInfo fileinfo(filePath);
		outputPath = QString("%1/%2-no-bg.png").arg(outputPath).arg(fileinfo.fileName());
	}
	QFile file(outputPath);
	if (!file.open(QIODevice::WriteOnly))
	{
		//ui->plainTextEdit->appendPlainText(QString("创建文件失败:%1").arg(filePath));
		return;
	}
	file.write(picRaw);
	file.close();
	//emit smallToBig(filePath, outputPath);

}

void QDownUpLoadImage::solveRecveImage()
{
	if (reply->error() == QNetworkReply::NoError)
	{
		QString itemGetStr = reply->readAll();

		Json::Reader reader;
		Json::Value root;
		if (reader.parse(itemGetStr.toStdString(), root))
		{
			int code = root["code"].asInt();
			if (code == 0)
			{
				std::string imagepath = root["imagepath"].asString();
				std::string oldimagepath = root["oldimagepath"].asString();
				QByteArray ba;
				ba = QByteArray(oldimagepath.c_str());
				ba = ba.fromBase64(ba);
				QString getoldimagepath = QString::fromUtf8(ba);

				int j = 0;
				j++;
				//g_utilTool->CompleteLoadImage(getoldimagepath,imagepath.c_str());
			}
			
		}

		int j = 0;
		j++;
	}
	else
	{
		QString strReplay = reply->errorString();
		int j = 0;
		j++;
		//?emit connectError(reply->errorString());
	}

}



void QDownUpLoadImage::clearData()
{
    filepath.clear();
    token.clear();
    i = 0;
}



.php
<?php

 $currentDateTime  =  date('YmdHis',time());
 $currentDate =  date('Ymd',time());


$imageName = rand(1111,9999)."_".date("His",time())."_".rand(1111,9999).'.png';


if (!is_dir($currentDate)){ //判断目录是否存在 不存在就创建
 mkdir($currentDate,0777,true);
}
$imageSrc= $currentDate."/". $imageName;

$oldimagepath=$_POST['oldimagepath'];
$recContent=$_POST['fileData'];
$data=base64_decode(str_replace(" ","+",($recContent)));
$r = file_put_contents($imageSrc, $data);

if (!$r) {
 $tmparr1=array('data'=>null,"code"=>1,"msg"=>"图片生成失败" );
 echo json_encode($tmparr1);
}else{
 $tmparr2=array('data'=>1,"code"=>0,"msg"=>"图片生成成功","imagepath"=>$imageSrc,"oldimagepath"=>$oldimagepath);
 echo json_encode($tmparr2);
}



?>



使用例子
QDownUpLoadImage m_RemoveBGConn;

m_RemoveBGConn.downImageUrl("http://127.0.0.1/design/1.jpg"); 下载

m_RemoveBGConn.postImageData("C:\\500.png"); 上传

 

上一篇:qt先生成json文件后程序启动时读取json文件在一组数据模拟下正常,换一组数据就出现乱码


下一篇:Qt和MFC的比较