jalik:ufs

v0.7.1_1Published 9 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

UploadFS

UploadFS is a package for the Meteor framework that aims to make file uploading easy, fast and configurable. Some important features are supported like the ability to start, stop or even abort a transfer, securing file access, transforming files on writing or reading...

If you want to support this package and feel graceful for all the work, please share this package with the community or feel free to send me pull requests if you want to contribute.

Also I'll be glad to receive donations, whatever you give it will be much appreciated.

Donate

Version 0.7.1

  • Adds default store permissions (UploadFS.config.defaultStorePermissions)
  • Fixes store permissions (#95)
  • Fixes HTTP Range result from stream (#94) : works with ufs-local and ufs-gridfs

Version 0.7.0_2

  • Adds support for Range request headers (to seek audio/video files)
  • Upgrades dependencies

Version 0.6.9

  • Adds ufs-mime.js file to handle mime related operations
  • Sets default file type to "application/octet-stream"
  • Detects automatically MIME type by checking file extension on upload (#84)
  • Fixes error thrown by UploadFS.Filter.checkContentType() when file type is empty
  • Fixes check(file, Object); into "ufsImportURL" method

Version 0.6.8

  • Passes full predicate in CRUD operations instead of just the ID
  • Removes file tokens when file is uploaded or removed
  • Adds the "originalUrl" attribute to files imported from URLs
  • Adds the "path" attribute to uploaded files corresponding to the relative URL of the file
  • Adds UploadFS.Store.prototype.getRelativeURL(path) to get the relative URL of a store
  • Adds UploadFS.Store.prototype.getFileRelativeURL(path) to get the relative URL of a file in a store
  • Adds UploadFS.addPathAttributeToFiles(where) to add the path attribute to existing files
  • Unblock the UploadFS.importFromURL()
  • Fixes file deletion during upload (stop uploading and removes temp file)

You can upgrade existing documents to add the path attribute by calling the UploadFS.addPathAttributeToFiles(where) which will upgrade all collections linked to any UploadFS store, the where option is not required, default predicate is {path: null}.

Version 0.6.7

  • Allows to define stores on server only, use the store name directly as a reference on the client
  • Fixes an error caused by the use of an upsert in multi-server environment (mongo)

Version 0.6.5

  • Fixes 504 Gateway timeout error when file is not served by UploadFS

Version 0.6.4

  • Allows to set temp directory permissions

Version 0.6.3

  • Fixes iOS and Android issues
  • Adds CORS support

Version 0.6.1

  • Brings a huge improvement to large file transfer
  • Uses POST HTTP method instead of Meteor methods to upload files
  • Simplifies code for future versions

Breaking changes

UploadFS.readAsArrayBuffer() is DEPRECATED

The method UploadFS.readAsArrayBuffer() is not available anymore, as uploads are using POST binary data, we don't need ArrayBuffer.

1UploadFS.selectFiles(function(ev){
2    UploadFS.readAsArrayBuffer(ev, function (data, file) {
3        let photo = {
4            name: file.name,
5            size: file.size,
6            type: file.type
7        };
8        let worker = new UploadFS.Uploader({
9            store: photosStore,
10            data: data,
11            file: photo
12        });
13        worker.start();
14    });
15});

The new code is smaller and easier to read :

1UploadFS.selectFiles(function(file){
2    let photo = {
3        name: file.name,
4        size: file.size,
5        type: file.type
6    };
7    let worker = new UploadFS.Uploader({
8        store: photosStore,
9        data: file,
10        file: photo
11    });
12    worker.start();
13});

Permissions are defined differently

Before v0.6.1 you would do like this :

1Photos.allow({
2    insert: function (userId, doc) {
3        return userId;
4    },
5    update: function (userId, doc) {
6        return userId === doc.userId;
7    },
8    remove: function (userId, doc) {
9        return userId === doc.userId;
10    }
11});

Now you can set the permissions when you create the store :

1PhotosStore = new UploadFS.store.Local({
2    collection: Photos,
3    name: 'photos',
4    path: '/uploads/photos',
5    permissions: new UploadFS.StorePermissions({
6        insert: function (userId, doc) {
7            return userId;
8        },
9        update: function (userId, doc) {
10            return userId === doc.userId;
11        },
12        remove: function (userId, doc) {
13            return userId === doc.userId;
14        }
15    }
16});

Testing

You can test the package by downloading and running UFS-Example which is simple demo of UploadFS.

Mobile Testing

In order to test on mobile builds, ROOT_URL and --mobile-server must be set to your computer's local IP address and port:

export ROOT_URL=http://192.168.1.7:3000 && meteor run android-device --mobile-server=http://192.168.1.7:3000

Installation

To install the package, execute this command in the root of your project :

meteor add jalik:ufs

If later you want to remove the package :

meteor remove jalik:ufs

Plugins

As the package is modular, you can add support for custom stores and even create one, it's easy.

Introduction

In file uploading, you basically have a client and a server, I haven't change those things. So on the client side, you create an uploader for each file transfer needed, while on the server side you only configure a store where the file will be saved.

In this documentation, I am using the UploadFS.store.Local store which saves files on the filesystem.

Configuration

You can access and modify settings via UploadFS.config.

1// Set default permissions for all stores (you can later overwrite the default permissions on each store)
2UploadFS.config.defaultStorePermissions = new UploadFS.StorePermissions({
3    insert: function (userId, doc) {
4        return userId;
5    },
6    update: function (userId, doc) {
7        return userId === doc.userId;
8    },
9    remove: function (userId, doc) {
10        return userId === doc.userId;
11    }
12});
13
14// Use HTTPS in URLs
15UploadFS.config.https = true;
16
17// Activate simulation for slowing file reading
18UploadFS.config.simulateReadDelay = 1000; // 1 sec
19
20// Activate simulation for slowing file uploading
21UploadFS.config.simulateUploadSpeed = 128000; // 128kb/s
22
23// Activate simulation for slowing file writing
24UploadFS.config.simulateWriteDelay = 2000; // 2 sec
25
26// This path will be appended to the site URL, be sure to not put a "/" as first character
27// for example, a PNG file with the _id 12345 in the "photos" store will be available via this URL :
28// http://www.yourdomain.com/uploads/photos/12345.png
29UploadFS.config.storesPath = 'uploads';
30
31// Set the temporary directory where uploading files will be saved
32// before sent to the store.
33UploadFS.config.tmpDir = '/tmp/uploads';
34
35// Set the temporary directory permissions.
36UploadFS.config.tmpDirPermissions = '0700';

Creating a Store (server)

Since v0.6.7, you can share your store between client and server or define it on the server only. Before v0.6.7, a store must be available on the client and the server.

A store is the place where your files are saved, it could be your local hard drive or a distant cloud hosting solution. Let say you have a Photos collection which is used to save the files info.

1Photos = new Mongo.Collection('photos');

What you need is to create the store that will will contains the data of the Photos collection. Note that the name of the store must be unique. In the following example we are using a local filesystem store. Each store has its own options, so refer to the store documentation to see available options.

1PhotosStore = new UploadFS.store.Local({
2    collection: Photos,
3    name: 'photos',
4    path: '/uploads/photos'
5});

Filtering uploads (server)

You can set an UploadFS.Filter to the store to define restrictions on file uploads. Filter is tested before inserting a file in the collection. If the file does not match the filter, it won't be inserted and will not be uploaded.

1PhotosStore = new UploadFS.store.Local({
2    collection: Photos,
3    name: 'photos',
4    path: '/uploads/photos',
5    // Apply a filter to restrict file upload
6    filter: new UploadFS.Filter({
7        minSize: 1,
8        maxSize: 1024 * 1000 // 1MB,
9        contentTypes: ['image/*'],
10        extensions: ['jpg', 'png']
11    })
12});

If you need a more advanced filter, you can pass your own method using the onCheck option.

1PhotosStore = new UploadFS.store.Local({
2    collection: Photos,
3    name: 'photos',
4    path: '/uploads/photos',
5    // Apply a filter to restrict file upload
6    filter: new UploadFS.Filter({
7        onCheck: function(file) {
8            if (file.extension !== 'png') {
9                return false;
10            }
11            return true;
12        }
13    })
14});

Transforming files (server)

If you need to modify the file before saving it to the store, you can to use the transformWrite option. If you want to modify the file before returning it (for display), then use the transformRead option. A common use is to resize/compress images to optimize the uploaded files. NOTE: Install the required libs (GM, ImageMagick, GraphicsMagicK or whatever you are using), these libs are not embedded in UploadFS.

1PhotosStore = new UploadFS.store.Local({
2    collection: Photos,
3    name: 'photos',
4    path: '/uploads/photos',
5    // Transform file when reading
6    transformRead: function (from, to, fileId, file, request) {
7        from.pipe(to); // this returns the raw data
8    }
9    // Transform file when writing
10    transformWrite: function (from, to, fileId, file) {
11        let gm = Npm.require('gm');
12        if (gm) {
13            gm(from)
14                .resize(400, 400)
15                .gravity('Center')
16                .extent(400, 400)
17                .quality(75)
18                .stream().pipe(to);
19        } else {
20            console.error("gm is not available", file);
21        }
22    }
23});

Copying files (since v0.3.6) (server)

You can copy files to other stores on the fly, it could be for backup or just to have alternative versions of the same file (eg: thumbnails). To copy files that are saved in a store, use the copyTo option, you just need to pass an array of stores to copy to.

1Files = new Mongo.Collection('files');
2Thumbnails128 = new Mongo.Collection('thumbnails-128');
3Thumbnails64 = new Mongo.Collection('thumbnails-64');
4
5Thumbnail128Store = new UploadFS.store.Local({
6    collection: Thumbnails128,
7    name: 'thumbnails-128',
8    path: '/uploads/thumbsnails/128x128',
9    transformWrite: function(readStream, writeStream, fileId, file) {
10        let gm = Npm.require('gm');
11        if (gm) {
12            gm(from)
13                .resize(128, 128)
14                .gravity('Center')
15                .extent(128, 128)
16                .quality(75)
17                .stream().pipe(to);
18        } else {
19            console.error("gm is not available", file);
20        }
21    }
22});
23
24Thumbnail64Store = new UploadFS.store.Local({
25    collection: Thumbnails64,
26    name: 'thumbnails-64',
27    path: '/uploads/thumbsnails/64x64',
28    transformWrite: function(readStream, writeStream, fileId, file) {
29        let gm = Npm.require('gm');
30        if (gm) {
31            gm(from)
32                .resize(64, 64)
33                .gravity('Center')
34                .extent(64, 64)
35                .quality(75)
36                .stream().pipe(to);
37        } else {
38            console.error("gm is not available", file);
39        }
40    }
41});
42
43FileStore = new UploadFS.store.Local({
44    collection: Files,
45    name: 'files',
46    path: '/uploads/files',
47    copyTo: [
48        Thumbnail128Store,
49        Thumbnail64Store
50    ]
51});

You can also manually copy a file to another store by using the copy() method.

1Backups = new Mongo.Collection('backups');
2
3BackupStore = new UploadFS.store.Local({
4    collection: Backups,
5    name: 'backups',
6    path: '/backups'
7});
8
9PhotosStore.copy(fileId, BackupStore, function(err, copyId, copyFile) {
10    !err && console.log(fileId + ' has been copied as ' + copyId);
11});

All copies contain 2 fields that references the original file, originalId and originalStore. So if you want to display a thumbnail instead of the original file you could do like this :

1<template name="files">
2    {{#each files}}
3        <img src="{{thumb.url}}">
4    {{/each}}
5</template>
1Template.files.helpers({
2    files: function() {
3        return Files.find();
4    },
5    thumb: function() {
6        return Thumbnails128.findOne({originalId: this._id});
7    }
8});

Or you can save the thumbnails URL into the original file, it's the recommended way to do it since it's embedded in the original file, you don't need to manage thumbnails subscriptions :

1Thumbnails128Store.onFinishUpload = function(file) {
2    Files.update({_id: file.originalId}, {$set: {thumb128Url: file.url}});
3};
4Thumbnails64Store.onFinishUpload = function(file) {
5    Files.update({_id: file.originalId}, {$set: {thumb64Url: file.url}});
6};

Setting permissions (server)

If you don't want anyone to do anything, you must define permission rules. By default, there is no restriction (except the filter) on insert, remove and update actions.

The permission system has changed since v0.6.1, you must define permissions like this :

1PhotosStore.setPermissions(new UploadFS.StorePermissions({
2    insert: function (userId, doc) {
3        return userId;
4    },
5    update: function (userId, doc) {
6        return userId === doc.userId;
7    },
8    remove: function (userId, doc) {
9        return userId === doc.userId;
10    }
11});

or when you create the store :

1PhotosStore = new UploadFS.store.Local({
2    collection: Photos,
3    name: 'photos',
4    path: '/uploads/photos',
5    permissions: new UploadFS.StorePermissions({
6        insert: function (userId, doc) {
7            return userId;
8        },
9        update: function (userId, doc) {
10            return userId === doc.userId;
11        },
12        remove: function (userId, doc) {
13            return userId === doc.userId;
14        }
15    }
16});

or you can set default permissions for all stores (since v0.7.1) :

1UploadFS.config.defaultStorePermissions = new UploadFS.StorePermissions({
2    insert: function (userId, doc) {
3        return userId;
4    },
5    update: function (userId, doc) {
6        return userId === doc.userId;
7    },
8    remove: function (userId, doc) {
9        return userId === doc.userId;
10    }
11});

Securing file access (server)

When returning the file for a HTTP request, you can do some checks to decide whether or not the file should be sent to the client. This is done by defining the onRead() method on the store.

Note: Since v0.3.5, every file has a token attribute when its transfer is complete, this token can be used as a password to access/display the file. Just be sure to not publish it if not needed. You can also change this token whenever you want making older links to be staled.

1{{#with image}}
2<a href="{{url}}?token={{token}}">
3    <img src="{{url}}?token={{token}}">
4</a>
5{{/with}}
1PhotosStore = new UploadFS.store.Local({
2    collection: Photos,
3    name: 'photos',
4    path: '/uploads/photos',
5    onRead: function (fileId, file, request, response) {
6        // Allow file access if not private or if token is correct
7        if (file.isPublic || request.query.token === file.token) {
8            return true;
9        } else {
10            response.writeHead(403);
11            return false;
12        }
13    }
14});

Handling store events and errors (client/server)

Some events are triggered to allow you to do something at the right moment on server side.

1PhotosStore = new UploadFS.store.Local({
2    collection: Photos,
3    name: 'photos',
4    path: '/uploads/photos',
5    // Called when file has been uploaded
6    onFinishUpload: function (file) {
7        console.log(file.name + ' has been uploaded');
8    },
9    // Called when a copy error happened
10    onCopyError: function (err, fileId, file) {
11        console.error('Cannot create copy ' + file.name);
12    }
13    // Called when a read error happened
14    onReadError: function (err, fileId, file) {
15        console.error('Cannot read ' + file.name);
16    }
17    // Called when a write error happened
18    onWriteError: function (err, fileId, file) {
19        console.error('Cannot write ' + file.name);
20    }
21});

Reading a file from a store (server)

If you need to get a file directly from a store, do like below :

1// Get the file from database
2let file = Photos.findOne({_id: fileId});
3
4// Get the file stream from the store
5let readStream = PhotosStore.getReadStream(fileId, file);
6
7readStream.on('error', Meteor.bindEnvironment(function (error) {
8    console.error(err);
9}));
10readStream.on('data', Meteor.bindEnvironment(function (data) {
11    // handle the data
12}));

Writing a file to a store (server)

If you need to save a file directly to a store, do like below :

1// Insert the file in database
2let fileId = store.create(file);
3
4// Save the file to the store
5store.write(stream, fileId, function(err, file) {
6    if (err) {
7        console.error(err);
8    }else {
9        console.log('file saved to store');
10    }
11});

Uploading files

Uploading from a local file (client)

When the store on the server is configured, you can upload files to it.

Here is the template to upload one or more files :

1<template name="upload">
2    <button type="button" name="upload">Select files</button>
3</template>

And there the code to upload the selected files :

1Template.upload.events({
2    'click button[name=upload]': function (ev) {
3        let self = this;
4
5        UploadFS.selectFiles(function (file) {
6            // Prepare the file to insert in database, note that we don't provide a URL,
7            // it will be set automatically by the uploader when file transfer is complete.
8            let photo = {
9                name: file.name,
10                size: file.size,
11                type: file.type,
12                customField1: 1337,
13                customField2: {
14                    a: 1,
15                    b: 2
16                }
17            };
18
19            // Create a new Uploader for this file
20            let uploader = new UploadFS.Uploader({
21                // This is where the uploader will save the file
22                // since v0.6.7, you can pass the store instance or the store name directly
23                store: PhotosStore || 'photos',
24                // Optimize speed transfer by increasing/decreasing chunk size automatically
25                adaptive: true,
26                // Define the upload capacity (if upload speed is 1MB/s, then it will try to maintain upload at 80%, so 800KB/s)
27                // (used only if adaptive = true)
28                capacity: 0.8, // 80%
29                // The size of each chunk sent to the server
30                chunkSize: 8 * 1024, // 8k
31                // The max chunk size (used only if adaptive = true)
32                maxChunkSize: 128 * 1024, // 128k
33                // This tells how many tries to do if an error occurs during upload
34                maxTries: 5,
35                // The File/Blob object containing the data
36                data: file,
37                // The document to save in the collection
38                file: photo,
39                // The error callback
40                onError: function (err) {
41                    console.error(err);
42                },
43                onAbort: function (file) {
44                    console.log(file.name + ' upload has been aborted');
45                },
46                onComplete: function (file) {
47                    console.log(file.name + ' has been uploaded');
48                },
49                onCreate: function (file) {
50                    console.log(file.name + ' has been created with ID ' + file._id);
51                },
52                onProgress: function (file, progress) {
53                    console.log(file.name + ' ' + (progress*100) + '% uploaded');
54                }
55                onStart: function (file) {
56                    console.log(file.name + ' started');
57                },
58                onStop: function (file) {
59                    console.log(file.name + ' stopped');
60                },
61            });
62
63            // Starts the upload
64            uploader.start();
65
66            // Stops the upload
67            uploader.stop();
68
69            // Abort the upload
70            uploader.abort();
71        });
72    }
73});

Notice : You can use UploadFS.selectFile(callback) or UploadFS.selectFiles(callback) to select one or multiple files, the callback is called with one argument that represents the File/Blob object for each selected file.

During uploading you can get some kind of useful information like the following :

  • uploader.getAverageSpeed() returns the average speed in bytes per second
  • uploader.getElapsedTime() returns the elapsed time in milliseconds
  • uploader.getRemainingTime() returns the remaining time in milliseconds
  • uploader.getSpeed() returns the speed in bytes per second

Importing file from a URL (server)

You can import a file from an absolute URL by using one of the following methods :

1let url = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
2let attr = { name: 'Google Logo', description: 'Logo from www.google.com' };
3
4// You can import directly from the store instance
5PhotosStore.importFromURL(url, attr, function (err, file) {
6    if (err) {
7        displayError(err);
8    } else {
9        console.log('Photo saved :', file);
10    }
11});
12
13// Or using the common UFS method (requires the store name)
14UploadFS.importFromURL(url, attr, storeName, callback);

WARNING: File type detection is based on the file name in the URL so if the URL is obfuscated it won't work (http://www.hello.com/images/123456 won't work, http://www.hello.com/images/123456.png will work).

NOTE: since v0.6.8, all imported files have the originalUrl attribute, this allows to know where the file comes from and also to do some checks before inserting the file with the StorePermissions.insert.

1PhotosStore = new UploadFS.Store.Local({
2    name: 'photos',
3    collection: Photos,
4    permissions: new UploadFS.StorePermissions({
5        insert: function(userId, file) {
6            // Check if the file is imported from a URL
7            if (typeof file.originalUrl === 'string') {
8                // allow or not by doing some checks
9            }
10        }
11    })
12});

Setting MIME types (server)

NOTE: only available since v0.6.9

UploadFS automatically detects common MIME types based on the file extension. So when uploading a file, if the file.type is not set, UploadFS will check in its MIME list and assign the corresponding MIME, you can also add your own MIME types.

1// Adds KML and KMZ MIME types detection
2UploadFS.addMimeType('kml', 'application/vnd.google-earth.kml+xml');
3UploadFS.addMimeType('kmz', 'application/vnd.google-earth.kmz');

If you want to get all MIME types :

1const MIME = UploadFS.getMimeTypes();

Displaying images (client)

To display a file, simply use the url attribute for an absolute URL or the path attribute for a relative URL.

NOTE: path is only available since v0.6.8

You can upgrade existing documents to add the path attribute by calling the UploadFS.addPathAttributeToFiles(where) which will upgrade all collections linked to any UploadFS store, the where option is not required, default predicate is {path: null}.

Here is the template to display a list of photos :

1<template name="photos">
2    <div>
3        {{#each photos}}
4            {{#if uploading}}
5                <img src="/images/spinner.gif" title="{{name}}">
6                <span>{{completed}}%</span>
7            {{else}}
8                <img src="{{url}}" title="{{name}}">
9            {{/if}}
10        {{/each}}
11    </div>
12</template>

And there the code to load the file :

1Template.photos.helpers({
2    completed: function() {
3        return Math.round(this.progress * 100);
4    },
5    photos: function() {
6        return Photos.find();
7    }
8});

Using template helpers (client)

Some helpers are available by default to help you work with files inside templates.

1{{#if isApplication}}
2    <a href="{{url}}">Download</a>
3{{/if}}
4{{#if isAudio}}
5    <audio src="{{url}}" controls></audio>
6{{/if}}
7{{#if isImage}}
8    <img src="{{url}}">
9{{/if}}
10{{#if isText}}
11    <iframe src={{url}}></iframe>
12{{/if}}
13{{#if isVideo}}
14    <video src="{{url}}" controls></video>
15{{/if}}