You are here

public function MongoFile::saveChunk in One Click Upload 7.2

Save chunk

Return value

bool

Throws

\Exception if upload size is invalid or some other unexpected error occurred.

Overrides File::saveChunk

File

flowphp/src/Flow/Mongo/MongoFile.php, line 75

Class

MongoFile
Notes:

Namespace

Flow\Mongo

Code

public function saveChunk() {
  try {
    $file = $this->request
      ->getFile();
    $chunkQuery = [
      'files_id' => $this
        ->getGridFsFile()['_id'],
      'n' => intval($this->request
        ->getCurrentChunkNumber()) - 1,
    ];
    $chunk = $chunkQuery;
    $data = file_get_contents($file['tmp_name']);
    $actualChunkSize = strlen($data);
    if ($actualChunkSize > $this->request
      ->getDefaultChunkSize() || $actualChunkSize < $this->request
      ->getDefaultChunkSize() && $this->request
      ->getCurrentChunkNumber() != $this->request
      ->getTotalChunks()) {
      throw new \Exception("Invalid upload! (size: {$actualChunkSize})");
    }
    $chunk['data'] = new \MongoBinData($data, 0);

    // \MongoBinData::GENERIC is not defined for older mongo drivers
    $this->config
      ->getGridFs()->chunks
      ->findAndModify($chunkQuery, $chunk, [], [
      'upsert' => true,
    ]);
    unlink($file['tmp_name']);
    $this
      ->ensureIndices();
    return true;
  } catch (\Exception $e) {

    // try to remove a possibly (partly) stored chunk:
    if (isset($chunkQuery)) {
      $this->config
        ->getGridFs()->chunks
        ->remove($chunkQuery);
    }
    throw $e;
  }
}