ostrio:files

v3.1.0•Published 2 weeks ago

support support Mentioned in Awesome ostrio:files GitHub stars

Files for Meteor.js

Stable, fast, robust, and well-maintained Meteor.js package for files management using MongoDB Collection API. Call .insertAsync() method to initiate a file upload and to insert new record into MongoDB collection after upload is complete. Calling .removeAsync() method would erase stored file and record from MongoDB Collection. And so on, no need to learn new APIs. Hackable via hooks and events. Supports uploads to AWS:S3, GridFS, Google Storage, DropBox, and other 3rd party storage.

ToC:

Key features

Installation:

Install ostrio:files from Atmosphere

meteor add ostrio:files

Requires Meteor 3.2 or newer (v3.1.0 and later).

ES6 Import:

Import in isomorphic location (e.g. on server and client)

1import { FilesCollection } from 'meteor/ostrio:files';

API overview

For detailed docs, examples, and API, read the documentation section.

Main methods:

  • FilesCollection Constructor [Isomorphic] - Initialize FilesCollection
  • insertAsync() [Client] - Upload a file to server, returns a Promise that resolves with the UploadInstance (FileUpload) when autoStart is true
  • link() [Isomorphic] - Generate downloadable link
  • find() [Isomorphic] - Find all files matching selector, returns FilesCursor instance
  • findOneAsync() [Isomorphic] - Find a single file record matching selector, returns FileCursor instance
  • removeAsync() [Isomorphic] - Asynchronously remove files from FilesCollection and "unlink" (e.g. remove) from Server
  • addFile() [Server] - Add local file to FilesCollection from FS
  • loadAsync() [Server] - Write file to FS and FilesCollection from remote URL
  • writeAsync() [Server] - Write Buffer to FS and FilesCollection

Constructor

[Isomorphic]. Initiate file's collection in the similar way to Mongo.Collection with optional settings related to file-uploads. Read full docs for FilesCollection Constructor in the API documentation.

1import { FilesCollection } from 'meteor/ostrio:files';
2new FilesCollection(FilesCollectionConfig);

Pass additional options to control upload-flow

1// shared: /imports/lib/collections/images.collection.js
2import { Meteor } from 'meteor/meteor';
3import { FilesCollection } from 'meteor/ostrio:files';
4
5const imagesCollection = new FilesCollection({
6  collectionName: 'images',
7  allowClientCode: false, // Disallow remove files from Client
8  onBeforeUpload(file) {
9    // Allow upload files under 10MB, and only in png/jpg/jpeg formats
10    if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.extension)) {
11      return true;
12    }
13    return 'Please upload image, with size equal or less than 10MB';
14  }
15});
16
17if (Meteor.isClient) {
18  // SUBSCRIBE TO ALL UPLOADED FILES ON THE CLIENT
19  Meteor.subscribe('files.images.all');
20}
21
22if (Meteor.isServer) {
23  // PUBLISH ALL UPLOADED FILES ON THE SERVER
24  // Demo only: publishes every file record to every client. Filter by `userId` in production, see docs/security.md
25  Meteor.publish('files.images.all', function () {
26    return imagesCollection.collection.find();
27  });
28}

Upload a file

1import { FilesCollection } from 'meteor/ostrio:files';
2const files = new FilesCollection(FilesCollectionConfig);
3files.insertAsync(config: InsertOptions, autoStart?: boolean): Promise<FileUpload | UploadInstance>;

Read full docs for insertAsync() method

Upload form (template):

1<template name="uploadForm">
2  {{#with currentUpload}}
3    Uploading <b>{{file.name}}</b>:
4    <span id="progress">{{progress.get}}%</span>
5  {{else}}
6    <input id="fileInput" type="file" />
7  {{/with}}
8</template>

Shared code:

1import { FilesCollection } from 'meteor/ostrio:files';
2const imagesCollection = new FilesCollection({collectionName: 'images'});
3export default imagesCollection; // import in other files

Client's code:

1import { Template } from 'meteor/templating';
2import { ReactiveVar } from 'meteor/reactive-var';
3Template.uploadForm.onCreated(function () {
4  this.currentUpload = new ReactiveVar(false);
5});
6
7Template.uploadForm.helpers({
8  currentUpload() {
9    return Template.instance().currentUpload.get();
10  }
11});
12
13Template.uploadForm.events({
14  async 'change #fileInput'(e, template) {
15    if (e.currentTarget.files && e.currentTarget.files[0]) {
16      // We upload only one file, in case
17      // multiple files were selected
18      const upload = await imagesCollection.insertAsync({
19        file: e.currentTarget.files[0],
20        chunkSize: 'dynamic'
21      }, false);
22
23      upload.on('start', function () {
24        template.currentUpload.set(this);
25      });
26
27      upload.on('end', function (error, fileObj) {
28        if (error) {
29          alert(`Error during upload: ${error}`);
30        } else {
31          alert(`File "${fileObj.name}" successfully uploaded`);
32        }
33        template.currentUpload.set(false);
34      });
35
36      await upload.start();
37    }
38  }
39});

For multiple file upload see this demo code.

Upload base64 string (introduced in v1.7.1):

1// As dataURI
2await imagesCollection.insertAsync({
3  file: 'data:image/png;base64,base64str…',
4  isBase64: true, // <— Mandatory
5  fileName: 'pic.png' // <— Mandatory
6});
7
8// As plain base64:
9await imagesCollection.insertAsync({
10  file: 'base64str…',
11  isBase64: true, // <— Mandatory
12  fileName: 'pic.png', // <— Mandatory
13  type: 'image/png' // <— Mandatory
14});

For more expressive example see Upload demo app

Stream files

To display files you can use fileURL template helper or link() method of FileCursor instance.

Template:

1<template name='file'>
2  <img src="{{imageFile.link}}" alt="{{imageFile.name}}" />
3  <!-- Same as: -->
4  <!-- <img src="{{fileURL imageFile}}" alt="{{imageFile.name}}" /> -->
5  <hr>
6  <video height="auto" controls="controls">
7    <source src="{{videoFile.link}}?play=true" type="{{videoFile.type}}" />
8    <!-- Same as: -->
9    <!-- <source src="{{fileURL videoFile}}?play=true" type="{{videoFile.type}}" /> -->
10  </video>
11</template>

Shared code:

1// imports/lib/collections/files.collection.js
2import { Meteor } from 'meteor/meteor';
3import { FilesCollection } from 'meteor/ostrio:files';
4
5export const imagesCollection = new FilesCollection({ collectionName: 'images' });
6export const videosCollection = new FilesCollection({ collectionName: 'videos' });
7
8if (Meteor.isServer) {
9  // Upload sample files on server's startup:
10  Meteor.startup(async () => {
11    await imagesCollection.loadAsync('https://raw.githubusercontent.com/veliovgroup/Meteor-Files/master/logo.png', {
12      fileName: 'logo.png'
13    });
14    await videosCollection.loadAsync('https://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4', {
15      fileName: 'Big-Buck-Bunny.mp4'
16    });
17  });
18
19  // Demo only: publishes every file record to every client. Filter by `userId` in production, see docs/security.md
20  Meteor.publish('files.images.all', function () {
21    return imagesCollection.collection.find();
22  });
23
24  Meteor.publish('files.videos.all', function () {
25    return videosCollection.collection.find();
26  });
27} else {
28  // Subscribe to file's collections on Client
29  Meteor.subscribe('files.images.all');
30  Meteor.subscribe('files.videos.all');
31}

Client's code. The synchronous findOne() works on the Client only. Use findOneAsync() on the Server.

1// imports/client/file/file.js
2import { Template } from 'meteor/templating';
3import '/imports/client/file/file.html';
4import { imagesCollection, videosCollection } from '/imports/lib/collections/files.collection.js';
5
6Template.file.helpers({
7  imageFile() {
8    return imagesCollection.findOne();
9  },
10  videoFile() {
11    return videosCollection.findOne();
12  }
13});

For more expressive example see Streaming demo app

Download button

Create collection available to Client and Server

1// imports/lib/collections/images.collection.js
2import { Meteor } from 'meteor/meteor';
3import { FilesCollection } from 'meteor/ostrio:files';
4const imagesCollection = new FilesCollection({ collectionName: 'images' });
5export default imagesCollection;
6
7if (Meteor.isServer) {
8  // Load sample image into FilesCollection on server's startup:
9  Meteor.startup(async () => {
10    await imagesCollection.loadAsync('https://raw.githubusercontent.com/veliovgroup/Meteor-Files/master/logo.png', {
11      fileName: 'logo.png',
12    });
13  });
14
15  // Demo only: publishes every file record to every client. Filter by `userId` in production, see docs/security.md
16  Meteor.publish('files.images.all', function () {
17    return imagesCollection.collection.find();
18  });
19} else {
20  // Subscribe on the client
21  Meteor.subscribe('files.images.all');
22}

Create template, call .link method on the FileCursor returned from file helper

1<!-- imports/client/file/file.html -->
2<template name='file'>
3  <a href="{{file.link}}?download=true" download="{{file.name}}" target="_parent">
4    {{file.name}}
5  </a>
6</template>

Create controller for file template with file helper that returns FileCursor with .link() method

1// imports/client/file/file.js
2import { Template } from 'meteor/templating';
3import '/imports/client/file/file.html';
4import imagesCollection from '/imports/lib/collections/images.collection.js';
5
6Template.file.helpers({
7  file() {
8    return imagesCollection.findOne();
9  }
10});

For more expressive example see Download demo

FAQ:

  1. Where are files stored by default?: by default if config.storagePath isn't set in Constructor options it equals assets/app/uploads/<collectionName> and is relative to the running script:
    • a. On development stage: yourDevAppDir/.meteor/local/build/programs/server. Note: All files will be removed as soon as your application rebuilds or you run meteor reset. To keep your storage persistent during development use an absolute path outside of your project folder, e.g. /data directory.
    • b. On production: yourProdAppDir/programs/server. Note: If using MeteorUp (MUP), Docker volumes must be added to mup.js, see MUP usage
  2. Cordova usage and development: To use Meteor-Files in a Cordova app, enable withCredentials; enable {allowQueryStringCookies: true} and {allowedCordovaOrigins: true} on both Client and Server (see security notes). For more details read Cookie's repository FAQ
  3. meteor-desktop usage and development: Meteor-Files can be used in meteor-desktop projects as well. As meteor-desktop works exactly like Cordova, all Cordova requirements and recommendations apply
  4. How to pause/continue upload and get progress/speed/remaining time?: see FileUpload instance returned from insertAsync method
  5. When using any of accounts packages - package accounts-base must be explicitly added to .meteor/packages above ostrio:files
  6. cURL/POST uploads - Take a look on POST-Example by @noris666
  7. In Safari (Mobile and Desktop) for DDP the algorithm reduces the chunk size, because Safari throws an error if a frame is too big. Switching to http transport (which has no such issue) is recommended for Safari. See #458
  8. Make sure you're using single domain for the Meteor app, and the same domain for hosting Meteor-Files endpoints, see #737 for details
  9. When requests are proxied to FilesCollection endpoint make sure protocol http/1.1 is used, see #742 for details

Awards:

Get Support:

Demo applications:

Fully-featured file-sharing app:

Other demos:

Support Meteor-Files project:

Contribution:

  • Want to help? Please check issues for open and tagged as help wanted issues;
  • Want to contribute? Read and follow PR rules. All PRs are welcome on dev branch. Please, always give expressive description to your changes and additions.

Supporters:

We would like to thank everyone who supports this project