===========================================
MongoDB\\GridFS\\Bucket::uploadFromStream()
===========================================

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

.. phpmethod:: MongoDB\GridFS\Bucket::uploadFromStream()

   Creates a new GridFS file and copies the contents of a readable stream to it.

   .. code-block:: php

      function uploadFromStream(
          string $filename,
          resource $source,
          array $options = []
      ): mixed

Parameters
----------

``$filename`` : string
  The ``filename`` of the file to create.

``$source`` : resource
  Readable stream, from which the new GridFS file's contents will be read.

``$options`` : array
  An array specifying the desired options.

  .. list-table::
     :header-rows: 1
     :widths: 20 20 80

     * - Name
       - Type
       - Description

     * - _id
       - mixed
       - Value to use as the file document identifier. Defaults to a new
         :php:`MongoDB\BSON\ObjectId <class.mongodb-bson-objectid>` object.

     * - chunkSizeBytes
       - integer
       - The chunk size in bytes. Defaults to the bucket's ``chunkSizeBytes``
         option.

     * - disableMD5
       - boolean
       - Whether to disable automatic MD5 generation when storing files.

         Defaults to ``false``. Only ``true`` will be supported in 2.0.

         .. versionadded:: 1.4

     * - metadata
       - array|object
       - User data for the ``metadata`` field of the file document. If not
         specified, the ``metadata`` field will not be set on the file document.

Return Values
-------------

The ``_id`` field of the metadata document associated with the newly created
GridFS file. If the ``_id`` option is not specified, a new
:php:`MongoDB\BSON\ObjectId <class.mongodb-bson-objectid>` object will be used
by default.

Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst

Examples
--------

.. code-block:: php

   <?php

   $bucket = (new MongoDB\Client)->test->selectGridFSBucket();

   $stream = fopen('php://temp', 'w+b');
   fwrite($stream, "foobar");
   rewind($stream);

   $id = $bucket->uploadFromStream('filename', $stream);

   var_dump($id);

The output would then resemble:

.. code-block:: none

   object(MongoDB\BSON\ObjectId)#3009 (1) {
     ["oid"]=>
     string(24) "5acf81017e21e816e538d883"
   }

See Also
--------

- :phpmethod:`MongoDB\GridFS\Bucket::openUploadStream()`
