4

我有一个QFile需要通过局域网发送的。为此,我通过以下方式将其转换QFileQByteArray

//! [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);
}

当我收到它时,我可以使用以下方法轻松转换它:

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();
    }
}

但是,我想知道文件名(例如Document.docx)或至少知道它的扩展名,以避免强迫用户确切知道他收到的文件类型。

理想情况下,当文件上传时,会提示接收方用户保存文件。例如:

  1. 发件人发送Document1.docx
  2. 接收者会收到提示,如果他/她想保存Document1.docx
  3. 根据接收者的决定,Document1.docx保存在接收者的工作站中。

所以,我的问题是:有什么方法可以知道 aQFile转换为 aQByteArray然后再次(在另一台计算机中)转换为 a 时的名称和扩展名QFile

4

2 回答 2

1

您只需使用QFile::readAll().

Q:有什么方法可以知道 QFile 转换为 QByteArray 时的名称和扩展名?

不,文件名和扩展名不一定插入文件的字节中。这取决于文件格式。例如,您可以制作具有特定扩展名的自定义文件,并将其名称和扩展名放在字节的开头。

您可以在发送文件的原始字节之前手动发送文件的名称和扩展名。在此之前,您可以发送名称和扩展名的长度以及文件中的字节数。这样您就知道有多少字节与名称、扩展名和原始字节相关。

于 2014-04-18T20:02:56.837 回答
0

您的特定问题的答案是否定的。尽管特定文件在数据的开头包含所谓的幻数(或签名),但该签名对于特定文件格式应该是唯一的。

但是您描述的问题似乎并不严重,因为您可以简单地将文件名字符串和扩展名字符串与文件内容分开发送。

于 2016-10-25T15:12:44.977 回答