Upload Media Using Meteor-Files

Learn how to upload media files in a MeteorJS application.

Meteor-Files

Meteor-Files is a third-party Meteor package that’s very efficient at uploading files for storage. It can store files on the server’s file system and in third-party storage like Amazon S3, Dropbox, GridFS, and so on. It’s compatible with most front-end frameworks used by Meteor. It supports resumable downloads and also provides functional hooks, which we can utilize to perform custom logic as a file is uploaded. Hooks such as onAfterUpload and onBeforeUpload can be used to perform custom logic on uploaded files.

Meteor-Files is installed on our project by running the following command on the terminal:

meteor add ostrio:files

Meteor-Files saves the path of the uploaded file in MongoDB. We can retrieve uploaded files using the same Meteor MongoDB API as find to pull documents out of collections.

The playground below demonstrates how to upload files using Meteor-Files.

Meteor-Files configuration

Open the imports/api/files.js file. On line 2, we import FilesCollection from the meteor/ostrio:files package. We create and export a Files object from the FilesCollection.

This Files object is the package configuration. Some keys like the storagePath indicate the location on the file system where the uploaded file is saved. In this example, we save uploaded files inside assets/app/uploads/uploadedFiles. The files are stored in the assets folder on the server.

There’s an onBeforeUpload hook that we can use to test the type of file the user is uploading to our server. The code widget below shows the onBeforeUpload hook. On line 3, we define the file type and file size that a user is allowed to upload to the server. The code below only permits a user to upload .pdf file types, image files with .png extensions, .jpg, and .jpeg files no larger than 10MB.

Get hands-on with 1200+ tech skills courses.