Method: Mongo::Grid::FSBucket#upload_from_stream

Defined in:
lib/mongo/grid/fs_bucket.rb

#upload_from_stream(filename, io, opts = {}) ⇒ BSON::ObjectId

Uploads a user file to a GridFS bucket. Reads the contents of the user file from the source stream and uploads it as chunks in the chunks collection. After all the chunks have been uploaded, it creates a files collection document for the filename in the files collection.

Examples:

Upload a file to the GridFS bucket.

fs.upload_from_stream('a-file.txt', file)

Parameters:

  • filename (String)

    The filename of the file to upload.

  • io (IO)

    The source io stream to upload from.

  • opts (Hash) (defaults to: {})

    The options for the write stream.

  • options (Hash)

    a customizable set of options

Options Hash (opts):

  • :file_id (Object)

    An optional unique file id. An ObjectId is generated otherwise.

  • :chunk_size (Integer)

    Override the default chunk size.

  • :metadata (Hash)

    User data for the ‘metadata’ field of the files collection document.

  • :content_type (String)

    The content type of the file. Deprecated, please use the metadata document instead.

  • :aliases (Array<String>)

    A list of aliases. Deprecated, please use the metadata document instead.

Returns:

  • (BSON::ObjectId)

    The ObjectId file id.

Since:

  • 2.1.0



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/mongo/grid/fs_bucket.rb', line 435

def upload_from_stream(filename, io, opts = {})
  open_upload_stream(filename, opts) do |stream|
    begin
      stream.write(io)
    # IOError and SystemCallError are for errors reading the io.
    # Error::SocketError and Error::SocketTimeoutError are for
    # writing to MongoDB.
    rescue IOError, SystemCallError, Error::SocketError, Error::SocketTimeoutError
      begin
        stream.abort
      rescue Error::OperationFailure
      end
      raise
    end
  end.file_id
end