Important: Please read the Qt Code of Conduct -

Sending a File with its name with QTcpSocket

  • Hello Everyone,

    this may seem easy but i'm having a hard time sending a File with its name to another Device using QTcpSocket and QTcpServer.

    Here's the Code of the Sender

    if (!
    printf("could not open File");
    printf("File opened!");
    qint64 Size = TCFile.size();
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly); 
    QString FileName = TCFile.fileName();		   
    out << quint32(0) << FileName;				   
    QByteArray	q = TCFile.readAll();			  
    out << (quint32)(block.size()) - sizeof(quint32);
    qint64 x = 0;
    while (x < Size)
    qint64 y = socket->write(q);
    x += y;

    The Server Side:

    QDataStream in (m_socket);
    if (m_Blocksize = 0) {
    	if (m_socket->bytesAvailable() < sizeof(quint32))
    	in >> m_Blocksize;
    if (m_socket->bytesAvailable() < m_Blocksize)
    QString FileName; 
    in >> FileName;
    QByteArray line = m_socket->readAll(); 
    QString FilePath = "C:\\test"; 
    QFile target(FilePath + "/" + FileName);
    if (! { //opening the File to write the incoming Data to it 
    	printf("can't open File for writing");
    	target.write(line); //Writing the byte Array line to the target file 
    	printf("File received \n");

    This doesn't work as i get the Error can't open File for writing. When I manually type the name of the file on the Server side it does work. But as I'm trying to send multiple files i want this to be done autmatically. How can i make the Code above work??

    Thanks !!

  • Hi,
    please correct the path to follow Qt platform independent convention. Like it's described in many places throughout the documentation, i.e. here:

  • @JohnSRV
    It may or may not be related to your error. But regardless you cannot write server/receiver code which relies on m_socket->bytesAvailable() and m_socket->readAll() cooperating to read everything the client has sent in one go. You need to understand that readAll() only reads whatever is presently available, and that may not be the complete data sent by the client.

    • Only repeated reading can achieve that. Rewrite your code receiver-side to use slots.
    • Or use QDataStream::startTransaction() etc. to hide this from your code level, but it still works that way internally.

    Look at the various Qt Fortune Client/Server examples.

Log in to reply