我正在编写一个图像上传小部件,它将数据发送到 PHP 脚本并从 PHP 脚本获取新上传的文件名作为 http 响应。
@jdi,这是一个问题,现在我得到“?”作为 qDebug() << rep->readAll() 的响应,所以第一个 readAll 会清除缓冲区。
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image->save(&buffer, "JPG");
QNetworkAccessManager *http=new QNetworkAccessManager(this);
QNetworkRequest r(QUrl("http://domain/test.php"));
QString bound="---------------------------723690991551375881941828858";
QByteArray data(QString("--"+bound+"\r\n").toAscii());
data += "Content-Disposition: form-data; name=\"action\"\r\n\r\n";
data += "\r\n";
data += QString("--" + bound + "\r\n").toAscii();
data += "Content-Disposition: form-data; name=\"file\"; filename=\"test.jpg\"\r\n";
data += "Content-Type: image/JPG\r\n\r\n";
data += bytes;
data += "\r\n";
data += QString("--" + bound + "\r\n").toAscii();
data += QString("--" + bound + "\r\n").toAscii();
data += "Content-Disposition: form-data; name=\"desc\"\r\n\r\n";
data += "Description for my image here :)\r\n";
data += "\r\n";
r.setRawHeader(QString("Accept-Encoding").toAscii(), QString("gzip,deflate").toAscii());
r.setRawHeader(QString("Content-Type").toAscii(),QString("multipart/form-data; boundary=" + bound).toAscii());
r.setRawHeader(QString("Content-Length").toAscii(), QString::number(data.length()).toAscii());
rep = http->post(r,data);
connect(http,SIGNAL(finished(QNetworkReply*)),this,SLOT(uploadFinished(QNetworkReply*)));
以及回调函数:
void UploadWidget::uploadFinished(QNetworkReply* r)
{
r->deleteLater();
if(r->error() == QNetworkReply::NoError) {
QByteArray data = r->readAll();
//QString s = r->readAll(); solved - readAll clears the buffer :)
}
}
我用 QByteArray b = rep->readAll() 迭代;for (int i = 0 ; i< b.size(); i++) { qDebug() << (char)b.at(i); 有什么方法可以将整个字节数组转换为 Qstring,因为我只得到一些符号
? 3、ÉE、VcD?? Ô â C ö f § 应该是“1这是一个测试1”