Search code examples
qtcastingqt5qnetworkaccessmanagerqnetworkreply

Qt5: download a file without saving to HDD


I'm trying to download a file in Qt5, but the file must not be located on the HDD after download. To clarify> My app will use a downloaded file to update some firmware, and I don't want the downloaded update to remain on the user's hard drive because it could get stolen.

So, I'm trying to make a QFile from QNetworkReply* but without saving it to some path on a hard drive.

I'm downloading a file using QNetworkAccessManager and storing the data into QNetworkReply. I always used to make a QFile with QNetworkReply*, but now I can't do that.

I have found the QTemporaryFile class where a file gets removed right after using it, but that still leaves user with some options of finding the file later.

I tried typecasting that QNetworkReply* as a QFile, but didn't manage to get that to work, seems like QFile can't be without a path on HDD.

Does anyone have any ideas how to do this, and how?

Thanks everyone.


Solution

  • Again not sure your intended end use case but since your data is small enough to hold in memory you can use a QByteArray or QBuffer and write into it from your QNetworkReply. QBuffer provides a QIODevice interface for the QByteArray so it may be a bit easier for you to work with.

    Make sure to open the QBuffer for read/write. See the simple example below from the Qt documentation, http://doc.qt.io/qt-5/qbuffer.html#details, below:

    QBuffer buffer;
    char ch;
    
    buffer.open(QBuffer::ReadWrite);
    buffer.write("Qt rocks!");
    buffer.seek(0);
    buffer.getChar(&ch);  // ch == 'Q'
    buffer.getChar(&ch);  // ch == 't'
    buffer.getChar(&ch);  // ch == ' '
    buffer.getChar(&ch);  // ch == 'r'
    

    That should allow you to read back the data and use as required without creating a file on the system.