Uploading a file using post() method of QNetworkAccessManager Uploading a file using post() method of QNetworkAccessManager windows windows

Uploading a file using post() method of QNetworkAccessManager


You're creating compressedFile on the stack, and passing a pointer to it to your QNetworkRequest (and ultimately your QNetworkAccessManager). As soon as you leave the method you're in, compressedFile is going out of scope. I'm surprised it's not crashing on you, though the behavior is undefined.

You need to create the QFile on the heap:

QFile *compressedFile = new QFile("temp"); 

You will of course need to keep track of it and then delete it once the post has completed, or set it as the child of the QNetworkReply so that it it gets destroyed when the reply gets destroyed later:

QFile *compressedFile = new QFile("temp"); compressedFile->open(QIODevice::ReadOnly);QNetworkReply *reply = netManager.post(QNetworkRequest(QUrl("http://mywebsite.com/upload") ), compressedFile); compressedFile->setParent(reply);


You can also schedule automatic deletion of a heap-allocated file using signals/slots

QFile* compressedFile = new QFile(...);QNetworkReply* reply = Manager.post(...);// This is where the tricks isconnect(reply, SIGNAL(finished()), reply, SLOT(deleteLater());connect(reply, SIGNAL(destroyed()), compressedFile, SLOT(deleteLater());

IMHO, it is much more localized and encapsulated than having to keep around your file in the outer class.

Note that you must remove the first connect() if you have your postFinished(QNetworkReply*) slot, in which you must then not forget to call reply->deleteLater() inside it for the above to work.