使用http协议中post请求方式上传数据通常使用“multipart/form-data”,一个完整的文件上传post请求如下:
1 POST http://www.example.com HTTP/1.1 2 #以表单方式上传文件 3 Content-Type: multipart/form-data 4 # 发送的数据 5 ------WebKitFormBoundaryPpL3BfPQ4cHShsBz 6 \r\n 7 Content-Disposition: form-data; name="file"; filename="qw.png"; 8 #上传的文件类型,注意与上面“content-type”区别 9 Content-Type: image/png\r\n; 10 \r\n 11 .............文件内容................ 12 .............文件内容................ 13 ------WebKitFormBoundaryPpL3BfPQ4cHShsBz
请求行(第一行)和请求头(第三行)可通过QNetworkRequest类组织,“content-disposition”、“content-type”、“文件真正内容”可通过QHttpPart类组织,QHttpMultiPart类负责组织第五行至第十三行。
上代码,阴影部分对应:
1 void MainWindow::on_uploadBtn_clicked() 2 { 3 // 1. 创建networkmanager对象 4 QNetworkAccessManager* pManager = new QNetworkAccessManager(this); 5 // 2. 发送数据 - post 6 QNetworkRequest request; 7 request.setUrl(QUrl("http://192.168.31.119:80/myupload")); 8 request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data"); 9 10 // post数据块 11 QFileInfo info(ui->filePath->text()); 12 QHttpPart part; 13 QString disp = QString("form-data; user=\"%1\"; filename=\"%2\") 14 .arg(xx).arg(xx); 15 QString sufix = info.suffix(); 16 //组织content-dispositon 17 part.setHeader(QNetworkRequest::ContentDispositionHeader, disp); 18 QFile *file = new QFile(ui->filePath->text()); 19 file->open(QFile::ReadOnly); 20 //组织真正文件内容 21 part.setBodyDevice(file); 22 // 传输的数据块的格式 23 /* json配置文件 24 { 25 ".mp3":"audio/mp3", 26 ".avi":"video/avi", 27 ".html":"text/html", 28 ".json":"application/json" 29 } 30 */ 31 //组织content -type 第九行 32 part.setHeader(QNetworkRequest::ContentTypeHeader, "xxxx"); 33 34 QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this); 35 //加上分界线,打包 36 multiPart->append(part); 37 //post方式发送出去 38 QNetworkReply* reply = pManager->post(request, multiPart /*QHttpMultiPart *multiPart*/); 39 connect(reply, &QNetworkReply::readyRead, this, [=](){ 40 // 接收数据 41 QByteArray all = reply->readAll(); 42 43 44 // 释放内存 45 // delete multiPart; 46 multiPart->deleteLater(); 47 file->close(); 48 file->deleteLater(); 49 reply->deleteLater(); 50 });