Alex Spataru Alex Spataru - 1 month ago 14
C++ Question

QFile to QByteArray save file name

I have a

QFile
that needs to be sent through a LAN network. In order to do so, I convert the
QFile
into
QByteArray
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
write(ba);
}


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
file.write(ba);
// Close the file
file.close();
}
}


However, I would like to know the file name (such as
Document.docx
) 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
    Document1.docx

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

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



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

Answer

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.