Chinaunix首页 | 论坛 | 博客
  • 博客访问: 530241
  • 博文数量: 71
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 159
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-13 12:37
个人简介

aaaaaaaaa

文章分类

全部博文(71)

文章存档

2013年(71)

我的朋友

分类: 嵌入式

2013-07-24 17:06:07

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

 

首先一个页面代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
    

上传文件

    
 
        文件名称(name):
        文件是否可见(visibility):(0:不可见;1:可见)
        *文件内容:
        
    

 

 QT的post代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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;
}

 

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


阅读(613) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~