Qt http表单(/form-data)上传文件——Qt

前言

http 表单格式的上传文件和以往我使用的上传文件不太一样所以记录一下,下次直接复制粘贴!

代码

这是我写的一段简单的测试代码,界面中只有一个按钮,通过点击按钮实现选择文件,上传文件等操作。

void MainWindow::on_pushButton_clicked()
{
   //选择文件
    QString filePath = QFileDialog::getOpenFileName(this,
         tr("添加附件"), "./", tr("Files (*.jpg *.png *.bmp *.gif *.zip "
                              "*.rar *.xls *.xlsx *.doc *.docx *.ppt *.pptx *.pdf)"));
    if(filePath=="")
        return;
     QFileInfo info(filePath);

     QString fileName=info.fileName();

    //设置multiPart 
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart filePart;
    QString header=QString("form-data; name=\"file\";filename=\"%1\"").arg(fileName);
    //filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(header));
    QFile *file = new QFile(filePath);
    file->open(QIODevice::ReadOnly);
    filePart.setBodyDevice(file);
    file->setParent(multiPart);
    // we cannot delete the file now, so delete it with the multiPart
    multiPart->append(filePart);

    QNetworkRequest request;
    request.setUrl(QUrl("yourUrl"));

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkReply *reply = manager->post(request, multiPart);
    multiPart->setParent(reply);
    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    QByteArray bytes=reply->readAll();
    qDebug()<

结束语

记录一下而已。

你可能感兴趣的:(Qt,Widgets)