protected function updateFile(FileInterface $file, $resource, $mimetype = NULL) {
    $uri = $file->getFileUri();

    $destination = fopen($uri, 'wb');
    if (!$destination) {
      throw new HttpException(500, "File $uri could not be opened to write.");
    }

    $content_length = stream_copy_to_stream($resource, $destination);

    fclose($destination);

    if ($content_length === FALSE) {
      throw new HttpException(500, "Request body could not be copied to $uri");
    }

    if ($content_length === 0) {
      // Clean up the newly created, empty file.
      unlink($uri);
      throw new HttpException(400, "No bytes were copied to $uri");
    }

    if (!empty($mimetype)) {
      $file->setMimeType($mimetype);
    }

    // Flush the image cache for the image so thumbnails get regenerated.
    image_path_flush($uri);
  }