I'm looking for a basic code samples of how to upload files to server with HTTP POST method on Qt.
My task: I have simple Qt program and I need to select any image file from the local host and upload it to the server. The selection part and GUI is simple and I have already done it, but with POST uploading I'm confused. In addition I have to say, that there is no authorization to upload file.
If someone already looking this topic?
PS: the reason why I'm asking and not coding my self is time, I need to get this method quick.
Thank you, all success solutions from my side will be posted here for others.
ADDED: Here is my code, that doesn't work yet. Upload site located 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
");
totalBytes.append("Content-Disposition: form-data; name="email"
");
totalBytes.append("
");
totalBytes.append("billgates@microsoft.com
");
totalBytes.append("--AaB03x
");
totalBytes.append("Content-Disposition: form-data; name="photo"; filename="" + bytes+ ""
");
totalBytes.append("Content-Transfer-Encoding: binary
");
totalBytes.append(file->readAll());
totalBytes.append("
");
totalBytes.append("--AaB03x--");
header.setContentLength(totalBytes.length());
httpRequestAborted = false;
httpGetId = http->request(header, totalBytes);
file->close();
}
and read answer function below:
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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…