bool HttpRequestProcessor::sendFile(QFile& file)
{
    writeString(_socket, "HTTP/1.");
    writeString(_socket, _httpVersion);
    if (file.open(QIODevice::ReadOnly))
    {
        writeString(_socket, " 200 OK\n");
        writeString(_socket, "Content-Length: ");
        writeString(_socket, QString::number(file.size()) + "\n");
        writeString(_socket, "Pragma: no-cache\n");
        writeString(_socket, "Cache-Control: no-store\n");
        writeString(_socket, "\n");
        _socket->flush();
        char data[66000];
        int bytesRead=0;
        int bytesWritten=0;
        while ((file.bytesAvailable() > 0) && (bytesWritten != -1))
        {
            //64KB-Häppchen der Datei lesen und versenden
            bytesRead = file.read(data, 1023);
            if (bytesRead != -1)
            {
                bytesWritten = _socket->write(data, bytesRead);
                _socket->waitForBytesWritten();
                _socket->flush();
                if (bytesRead != bytesWritten)
                {
                    std::cerr << "error while sending data" << std::endl;
                }
            }
        }
    }
    else
    {
        this->send500();
        _socket->flush();
        return false;
    }
    //TODO: Header, die zum Dateiinhalt passen
    //TODO: Dateiinhalt senden
    //TODO: Bei Fehler false zurückgeben
    //writeString(_socket, "<!DOCTYPE html>\n<html><head><title>Bad request</title></head><body><p>400 Bad Request</p></body></html>");
    _socket->flush();
    
    return true;
}
Esempio n. 2
0
QFile *FileExplorer::openFileForUpload() {
  QString fileName = QFileDialog::getOpenFileName(
      this->baseWidget, tr("Select file"), QDir::currentPath()
  );

  if (! fileName.isEmpty()){
    QFile *file = new QFile(fileName);

    if (! file->exists()) {
      QMessageBox::information(
          this->baseWidget,tr("File explorer"), 
          tr("Cannot load %1.").arg(fileName)
      );
      return NULL;
    }

    QFileInfo fInfo(*file);
    uint byteCount = file->bytesAvailable();

    if (! fInfo.isFile()) {
        QMessageBox::information(
           this->baseWidget, tr("Uploader"), 
	   tr("%1. is not a regular file").arg(fileName)
        );
    } else if (! file->isReadable()) {
        QMessageBox::information(
           this->baseWidget, tr("Uploader"), 
           tr("No read permissions for %1.").arg(fileName)
        );
    } else if (! byteCount) {
        QMessageBox::information(
           this->baseWidget, tr("Uploader"), 
           tr("Attempting to upload an empty file")
        );
    } else { // Good for return
        return file;
    }

    // By this point, release memory
    delete file;
  }

  return NULL;
}