Alex Spataru Alex Spataru - 2 years ago 326
C++ Question

QFile to QByteArray save file name

I have a

that needs to be sent through a LAN network. In order to do so, I convert the
by doing:

//! [Inside a QTcpSocket class]

// Get the file name using a QFileDialog
QFile file(QFileDialog::getOpenFileName(NULL, tr("Upload a file")));

// If the selected file is valid, continue with the upload
if (!file.fileName().isEmpty) {
// Read the file and transform the output to a QByteArray
QByteArray ba = file.readAll();

// Send the QByteArray

When I receive it, I can transform it easily by using:

void saveFile(QByteArray ba) {
// Ask the user where he/she wants to save the file
QFile file(QFileDialog::getSaveFileName(NULL, tr("Save file")));

// Check that the path is valid
if (!file.fileName().isEmpty()) {
// Write contents of ba in file
// Close the file

However, I would like to know the file name (such as
) or at least know its extension to avoid forcing the user to know exactly which file type he has received.

Ideally, when the file is uploaded, the receiver user will be prompted to save the file. For example:

  1. Sender sends

  2. Receiver gets prompted if he/she wants to save

  3. Based on receiver's decision,
    is saved in receiver's workstation.

So, my question is: Is there any way to know the name and extension of a
when its transformed into a
and then transformed again (in another computer) into a

Answer Source

You just read the raw bytes of a file using QFile::readAll().

Q: Is there any way to know the name and extension of a QFile when its transformed into a QByteArray?

No. The file name and extension is not necessarily inserted in bytes of a file. It depends on the file format. For example you can make your custom file with a specific extension and put its name and extension at the begging of the bytes.

You can send the name and extension of the file manually before sending the raw bytes of the file. Before that you can send the length of name and extension and the number of bytes in file. This way you know how many bytes are related to name, extension and raw bytes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download