FileDisplayResponse.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * @copyright 2016 Roeland Jago Douma <roeland@famdouma.nl>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Roeland Jago Douma <roeland@famdouma.nl>
  7. * @author Kate Döen <kate.doeen@nextcloud.com>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OCP\AppFramework\Http;
  26. use OCP\AppFramework\Http;
  27. use OCP\Files\File;
  28. use OCP\Files\SimpleFS\ISimpleFile;
  29. /**
  30. * Class FileDisplayResponse
  31. *
  32. * @since 11.0.0
  33. * @template S of int
  34. * @template H of array<string, mixed>
  35. * @template-extends Response<int, array<string, mixed>>
  36. */
  37. class FileDisplayResponse extends Response implements ICallbackResponse {
  38. /** @var File|ISimpleFile */
  39. private $file;
  40. /**
  41. * FileDisplayResponse constructor.
  42. *
  43. * @param File|ISimpleFile $file
  44. * @param S $statusCode
  45. * @param H $headers
  46. * @since 11.0.0
  47. */
  48. public function __construct(File|ISimpleFile $file, int $statusCode = Http::STATUS_OK, array $headers = []) {
  49. parent::__construct($statusCode, $headers);
  50. $this->file = $file;
  51. $this->addHeader('Content-Disposition', 'inline; filename="' . rawurldecode($file->getName()) . '"');
  52. $this->setETag($file->getEtag());
  53. $lastModified = new \DateTime();
  54. $lastModified->setTimestamp($file->getMTime());
  55. $this->setLastModified($lastModified);
  56. }
  57. /**
  58. * @param IOutput $output
  59. * @since 11.0.0
  60. */
  61. public function callback(IOutput $output) {
  62. if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
  63. $output->setHeader('Content-Length: ' . $this->file->getSize());
  64. $output->setOutput($this->file->getContent());
  65. }
  66. }
  67. }