QHttpMultiPart:将文件发布到PHP脚本

时间:2013-06-21 12:19:15

标签: php qt qt5 qt4.8 qtnetwork

我在Qt 5工作并且正在努力进行分段上传。我的脚本尽可能接近docs

 QUrl testUrl("http://localhost/upload/test.php");
 QNetworkRequest request(testUrl);


 QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

 QString preview_path  = "C:/preview.jpg";
 QHttpPart previewPathPart;
 previewPathPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"preview_path\""));
 previewPathPart.setBody(preview_path.toLatin1());

 QHttpPart previewFilePart;
 previewFilePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant( "image/jpeg"));
 previewFilePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"preview_file\""));
 QFile *file = new QFile(preview_path);

 if (!file->exists()) {
     emit error(tr("Upload Error. File does not exist: ") + preview_path);
     return;
 }
 file->open(QIODevice::ReadOnly);
 previewFilePart.setBodyDevice(file);
 file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart

 multiPart->append(previewPathPart);
 multiPart->append(previewFilePart);

 reply = networkManager->post(request, multiPart);
 multiPart->setParent(reply); // delete the multiPart with the reply

 connect(reply, SIGNAL(finished()),
          this, SLOT  (uploadReply()));

 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
          this, SLOT  (uploadError(QNetworkReply::NetworkError)));

 connect(reply, SIGNAL(uploadProgress(qint64, qint64)),
          this, SLOT  (uploadProgress(qint64, qint64)));

然后我的uploadReply()插槽只打印回复:

QString data = (QString) reply->readAll();
qDebug() << data;

我已经使上传脚本尽可能简单,并在XAMPP中使用Apache / 2.2.21和PHP 5.3.8运行。我的upload_max_filesize和post_max_size是1000M。

echo "preview_path: " . (isset($_POST['preview_path']) ? $_POST['preview_path'] : "not set") . "\r\n";
echo "preview_file exists: " . (isset($_POST['preview_file']) ?  "true" : "false" ). "\r\n";
echo '$_FILES: ';
print_r($_FILES);
echo "preview_file content: " . $_POST['preview_file'];

我的进度插槽显示了大致正确的上传字节数。

但输出显示:

 preview_path: C:/preview.jpg
 preview_file exists: true
 $_FILES: Array
 (
 )
 preview_file content: ????

看起来这些字节是作为$ _POST变量而不是$ _FILE提交的,因为它们应该是? apache日志中没有错误。我该怎么调试呢?

1 个答案:

答案 0 :(得分:8)

解决!

感谢this question提示 - 我在QHttpPart的内容处理中添加了'filename',现在按预期上传。我认为文件名是可选的,但似乎在这种情况下工作。希望这有助于其他人!

QString preview_name = "preview.jpg";

QHttpPart previewFilePart;
previewFilePart.setHeader(QNetworkRequest::ContentTypeHeader,    QVariant("image/jpeg"));
previewFilePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"preview_file\"; filename=\""+ preview_name + "\""));