【问题标题】:Upload file with POST method on Qt4在 Qt4 上使用 POST 方法上传文件
【发布时间】:2011-02-07 08:22:28
【问题描述】:

我正在寻找有关如何在 Qt 上使用 HTTP POST 方法将文件上传到服务器的基本代码示例。

我的任务:我有一个简单的 Qt 程序,我需要从本地主机中选择任何图像文件并将其上传到服务器。选择部分和 GUI 很简单,我已经完成了,但是对于 POST 上传我很困惑。另外不得不说,上传文件是没有权限的。

如果有人已经在关注这个主题?

PS:我之所以问而不是编写自己的代码是时间,我需要快速获得此方法。

谢谢你,我这边的所有成功解决方案都会在这里发布给其他人。

添加:这是我的代码,它还不能工作。上传站点位于here

void    CDialog::on_uploadButton_clicked() {

    QFileInfo fileInfo(absPathLineEdit->text());

    if (!fileInfo.exists()) {
        QMessageBox::information(this, 
            tr("Information"), 
            tr("File doesn't exists! Please, select another image."));
        return;
    }

    file = new QFile(fileInfo.filePath());
    if (!file->open(QIODevice::ReadOnly)) {
        QMessageBox::information(this,
            tr("Information"),
            tr("Unable to open file for reading!"));
        return;
    }

    QString host = "http://data.cod.ru";

    QUrl url(host);

    QHttp::ConnectionMode mode = QHttp::ConnectionModeHttp;
    http->setHost(url.host(), mode, (url.port() == -1) ? 80 : url.port());

    QHttpRequestHeader header("POST", "/", 1, 1);
    header.setValue("Host", "data.cod.ru");
    header.setValue("Content-type", "multipart/form-data, boundary=AaB03x");
    header.setValue("Cache-Control", "no-cache");
    header.setValue("Accept", "*/*");

    QByteArray bytes(fileInfo.filePath().toUtf8());
    QByteArray totalBytes;
    totalBytes.append("--AaB03x\r\n");
    totalBytes.append("Content-Disposition: form-data; name=\"email\"\r\n");
    totalBytes.append("\r\n");
    totalBytes.append("billgates@microsoft.com\r\n");
    totalBytes.append("--AaB03x\r\n");
    totalBytes.append("Content-Disposition: form-data; name=\"photo\"; filename=\"" + bytes+ "\"\r\n");
    totalBytes.append("Content-Transfer-Encoding: binary\r\n\r\n");
    totalBytes.append(file->readAll());
    totalBytes.append("\r\n");
    totalBytes.append("--AaB03x--");

    header.setContentLength(totalBytes.length());

    httpRequestAborted = false;
    httpGetId = http->request(header, totalBytes);

    file->close();
}

并阅读下面的答案功能:

void    CDialog::httpRequestFinished(int requestId, bool error) {

    if (requestId != httpGetId)
        return;

    if (httpRequestAborted) {
        if (file) {
            file->close();
//          file->remove();
//          delete file;
            file = 0;
        }
        return;
    }

    if (requestId != httpGetId)
        return;

    file->close();

    if (error) {
//      file->remove();
        QMessageBox::information(this, tr("HTTP"),
            tr("Download failed: %1.")
            .arg(http->errorString()));
    } else {
        QByteArray data = http->readAll();
        QFile *dataFile = new QFile("answer.txt");
        dataFile->open(QIODevice::WriteOnly | QIODevice::Text);
        dataFile->write(data);
        dataFile->flush();
        dataFile->close();
    }

//  delete file;
    file = 0;
}

【问题讨论】:

    标签: qt post upload


    【解决方案1】:

    我看到您正在尝试使用 QHTTP 和 QHttpRequestHeader 类。 QT 文档说这些已被弃用:

    这个类已经过时了。它提供 保持旧的源代码正常工作。我们 强烈建议不要在 新代码。

    所以,正如之前建议的那样;我建议您使用QNetworkAccessManager 来做您想做的事情

    至于你原来的问题;您仍然可以使用 QHTTP 上传文件;我相信实际的请求标头结构取决于您尝试访问的特定站点。在这种情况下,wireshark 之类的工具会很有帮助。请检查下面的代码是否适合您,如果返回 302 响应,它应该从主文件夹上传 test1.jpg 文件并将其链接转储到服务器上。

    void MainWindow::on_pushButton_clicked()
    {   
        http = new QHttp(this); // http declared as a member of MainWindow class 
        connect(http, SIGNAL(requestFinished(int,bool)), SLOT(httpRequestFinished(int, bool)));
    
        QString boundary = "---------------------------723690991551375881941828858";
    
        // action
        QByteArray data(QString("--" + boundary + "\r\n").toAscii());
        data += "Content-Disposition: form-data; name=\"action\"\r\n\r\n";
        data += "file_upload\r\n";
    
        // file
        data += QString("--" + boundary + "\r\n").toAscii();
        data += "Content-Disposition: form-data; name=\"sfile\"; filename=\"test1.jpg\"\r\n";
        data += "Content-Type: image/jpeg\r\n\r\n";
    
        QFile file("/home/test1.jpg");
        if (!file.open(QIODevice::ReadOnly))
            return;
    
        data += file.readAll();
        data += "\r\n";
    
        // password
        data += QString("--" + boundary + "\r\n").toAscii();
        data += "Content-Disposition: form-data; name=\"password\"\r\n\r\n";
        //data += "password\r\n"; // put password if needed
        data += "\r\n";
    
        // description
        data += QString("--" + boundary + "\r\n").toAscii();
        data += "Content-Disposition: form-data; name=\"description\"\r\n\r\n";
        //data += "description\r\n"; // put description if needed
        data += "\r\n";
    
        // agree
        data += QString("--" + boundary + "\r\n").toAscii();
        data += "Content-Disposition: form-data; name=\"agree\"\r\n\r\n";
        data += "1\r\n";
    
        data += QString("--" + boundary + "--\r\n").toAscii();
    
        QHttpRequestHeader header("POST", "/cabinet/upload/");
        header.setValue("Host", "data.cod.ru");
        header.setValue("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.9) Gecko/20100401 Ubuntu/9.10 (karmic) Firefox/3.5.9");
        header.setValue("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        header.setValue("Accept-Language", "en-us,en;q=0.5");
        header.setValue("Accept-Encoding", "gzip,deflate");
        header.setValue("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
        header.setValue("Keep-Alive", "300");
        header.setValue("Connection", "keep-alive");
        header.setValue("Referer", "http://data.cod.ru/");
    
        //multipart/form-data; boundary=---------------------------723690991551375881941828858
    
        header.setValue("Content-Type", "multipart/form-data; boundary=" + boundary);
        header.setValue("Content-Length", QString::number(data.length()));
    
        http->setHost("data.cod.ru");
        http->request(header, data);
    
        file.close();
    }
    
    void MainWindow::httpRequestFinished(int, bool)
    {
        QHttpResponseHeader responce = http->lastResponse();
        if (responce.statusCode()==302)
        {
            qDebug() << "file accepted; get it from:";
            qDebug() << "data.cod.ru" << responce.value("Location");
        }
    }
    

    在 MainWindow 类的信号部分中声明的 httpRequestFinished

    希望这会有所帮助,女贞 ;)

    【讨论】:

    • @serge_gubenko:非常感谢,祝你好运。这段代码对我有用! :) Спасибо!
    【解决方案2】:

    另外,我今天发现了不错的代码:link text

    它是基于Qt4的上传/下载应用,里面有QNetworkAccessManager管理的全套POST头,所以对初学者很有帮助。

    所有者: 僵硬的.ru

    提交者: 霍克斯诺克斯

    【讨论】:

    • 太棒了!可以很容易地用于上传到基于 Flask 的应用程序
    【解决方案3】:

    使用 QNetworkAccessManager。

    manager.post(your_qhttpnetworkrequest, your_image_qfile);
    

    【讨论】:

      【解决方案4】:
      QPixmap pix(path);
      QByteArray bytes, data;
      QBuffer buffer(&bytes);
      if(!buffer.open(QIODevice::WriteOnly)) {
          return;
      }
      
      pix.save(&buffer, "JPG");  
      

      data.append("Content-Disposition: form-data; name=\"photo\"; filename=\"-\"\r\n"); data.append("内容类型:图片/jpg\r\n\r\n"); //data.append("Content-Transfer-Encoding: binary\r\n"); data.append(字节); data.append("\r\n"); data.append("--Asrf456BGe4h\r\n");

      【讨论】:

        猜你喜欢
        • 2018-02-27
        • 1970-01-01
        • 2014-02-13
        • 1970-01-01
        • 2016-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-17
        相关资源
        最近更新 更多