QT之旅——post 文件

最近要用到QT里面的qhttp或者QNetworkAccessManager post一个文件到后台。post一个简单的form还是比较容易,from如果是multipart/form-data类型的话,那就比较复杂,网上收集了一些资料,记录了下来。

 

首先一个页面代码如下:


<html>
<head></head>
<body>
	<h2>上传文件</h2>
	<form action="/gcd/uploadFileAction.json" method="post" enctype="multipart/form-data">

		文件名称(name):<input type="text" name="name"><br>
		文件是否可见(visibility):<input type="text" name="visibility">(0:不可见;1:可见)<br>
		*文件内容:<input type="file" name="file">
		<input type="submit">
	</form>
</body>
</html>

 

 QT的post代码如下:

bool uploadFile(std::string localPath)
{
    if(m_strFname == "")
        return false;

    QFile file(QString(localPath.c_str()));
    if (!file.open(QIODevice::ReadOnly))
    {
        file.close();
        return false;
    }

    QUrl url = QString(“your host”);
    url.setPort(1234);
    url.setPath(“your http path”);

    QString crlf="\r\n";
    qsrand(QDateTime::currentDateTime().toTime_t());
    QString b=QVariant(qrand()).toString()+QVariant(qrand()).toString()+QVariant(qrand()).toString();
    QString boundary="---------------------------"+b;
    QString endBoundary=crlf+"--"+boundary+"--"+crlf;
    QString contentType="multipart/form-data; boundary="+boundary;
    boundary="--"+boundary+crlf;
    QByteArray bond=boundary.toAscii();
    QByteArray send;

    send.append(bond);
    boundary = crlf + boundary;
    bond = boundary.toAscii();
    send.append(QString("Content-Disposition: form-data; name=\"name\""+crlf).toAscii());
    send.append(QString("Content-Transfer-Encoding: 8bit"+crlf).toAscii());
    send.append(crlf.toAscii());
    send.append(QString("文件名称").toUtf8());



    send.append(bond);
    send.append(QString("Content-Disposition: form-data; name=\"visibility\""+crlf).toAscii());
    send.append(QString("Content-Transfer-Encoding: 8bit"+crlf).toAscii());
    send.append(crlf.toAscii());
    send.append(QString("0").toUtf8());


 
    send.append(bond);
    send.append(QString("Content-Disposition: form-data; name=\"file\"; filename=\""+QString(localPath.c_str())+"\""+crlf).toAscii());
    //send.append(QString("Content-Type: "+fileMimes.at(i)+crlf+crlf).toAscii());
        send.append(QString("Content-Transfer-Encoding: 8bit"+crlf).toAscii());
        send.append(crlf.toAscii());
    send.append(file.readAll());

    send.append(endBoundary.toAscii());

    file.close();

    QNetworkRequest req(url);
    req.setHeader(QNetworkRequest::ContentTypeHeader, contentType.toAscii());
    req.setHeader(QNetworkRequest::ContentLengthHeader, QVariant(send.size()).toString());

QNetworkAccessManager qam;
   qam.post(req,send);

    return true;
}

 

可能有问题,先到这里吧。

 

 

转载于:https://www.cnblogs.com/tuojian/archive/2011/11/30/2268666.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值