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

.. default-domain:: mongodb

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

Definition
----------

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

   Opens a writable stream for a new GridFS file.

   .. code-block:: php

      function openUploadStream(
          string $filename,
          array $options = []
      ): resource

Parameters
----------

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

``$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
-------------

A writable stream resource.

Behavior
--------

Chunk documents will be created as data is written to the writable stream. The
metadata document will be created when the writable stream is closed.

Examples
--------

.. code-block:: php

   <?php

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

   $uploadStream = $bucket->openUploadStream('filename');
   fwrite($uploadStream, 'foobar');
   fclose($uploadStream);

   $downloadStream = $bucket->openDownloadStreamByName('filename');
   var_dump(stream_get_contents($downloadStream));

The output would then resemble:

.. code-block:: none

   string(6) "foobar"

See Also
--------

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