In Qt I need to send a sqlite file (binary file) up to a website using post. So what I do is that I open the file and try to read the content of it into a QByteArray that I with help of QNetworkRequest can send to the server. I can handle the request as the file is sent to the server but the file is just empty. Am开发者_StackOverflow社区 I reading the content of the sqlite file wrong? (I know that the file excist) Can you see anything wrong with my code?
QByteArray data;
QFile file("database.sqlite");
if (!file.open(QIODevice::ReadWrite))
return;
QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_6);
in >> data ;
QString boundary;
QByteArray dataToSend; // byte array to be sent in POST
boundary="-----------------------------7d935033608e2";
QString body = "\r\n--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name=\"database\"; filename=\"database.sqlite\"\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += data;
body += "\r\n--" + boundary + "--\r\n";
dataToSend = body.toAscii();
QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(this);
QNetworkRequest request(QUrl("http://www.mydomain.com/upload.aspx"));
request.setRawHeader("Content-Type","multipart/form-data; boundary=-----------------------------7d935033608e2");
request.setHeader(QNetworkRequest::ContentLengthHeader,dataToSend.size());
connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(sendReportToServerReply(QNetworkReply*)));
QNetworkReply *reply = networkAccessManager->post(request,dataToSend); // perform POST request
Do not use a QString to write the body, use a QByteArray instead. The line body += data; will in most cases not append the whole file.
data is a QByteArray and when transformed into a QString will be truncated at the first \0 . Your uploaded file will be not be usable.
Use the example provided in the link from one of the answers.
You don't need a QDataStream. Just do
body += file.readAll()
精彩评论