QT之旅——post 文件
http://www.cnblogs.com/tuojian/archive/2011/11/30/2268666.html
最近要用到QT里面的qhttp或者QNetworkAccessManager post一个文件到后台。post一个简单的form还是比较容易,from如果是multipart/form-data类型的话,那就比较复杂,网上收集了一些资料,记录了下来。
首先一个页面代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<
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代码如下:
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
;
}
|
可能有问题,先到这里吧。