From 46a69a072a35702b475328091e698cf8d2dd9ded Mon Sep 17 00:00:00 2001 From: Tim Canty Date: Wed, 13 Apr 2016 17:39:14 -0400 Subject: [PATCH] [FEATURE] Uses accept field to validate provided filetypes --- README.md | 1 + addon/components/file-picker.js | 29 ++++++++++++++++++++++- tests/unit/components/file-picker-test.js | 20 +++++++++++++++- 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 299e912..8f995ff 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ It supports: * `accept` default `*` * `multiple` default `false` * `selectOnClick` default `true` +* `validateExtensions` default `true` * `dropzone` default `true` * `preview` default `true` * `progress` default `true` diff --git a/addon/components/file-picker.js b/addon/components/file-picker.js index d0fa5d6..bf64bb7 100644 --- a/addon/components/file-picker.js +++ b/addon/components/file-picker.js @@ -25,6 +25,7 @@ export default Component.extend({ dropzone: true, progress: true, showProgress: false, + validateExtension: true, hideFileInput: true, readAs: 'readAsFile', selectOnClick: true, @@ -73,13 +74,39 @@ export default Component.extend({ } }, - handleFiles: function(files) { + _invalidExtension: function(files) { + let accept = this.get('accept'); + + if (accept === '*') { + return; + } + + let validExtensions = accept.split(','); + + let fileExtensions = files.map(file => `.${file.filename.split('.').slice(-1)[0]}`); + + return fileExtensions.some(extension => validExtensions.indexOf(extension) === -1); + }, + + _validate: function(files) { if (typeof(this.filesAreValid) === 'function') { if (!this.filesAreValid(files)) { return; } } + if (!this.get('validateExtension')) { + return; + } + + return !this._invalidExtension(files); + }, + + handleFiles: function(files) { + if (!this._validate(files)) { + return; + } + if (this.get('preview')) { this.updatePreview(files); } diff --git a/tests/unit/components/file-picker-test.js b/tests/unit/components/file-picker-test.js index 6224459..0c93a8d 100644 --- a/tests/unit/components/file-picker-test.js +++ b/tests/unit/components/file-picker-test.js @@ -90,4 +90,22 @@ test('it shows file input', function(assert) { this.render(); assert.equal(component.$('input:hidden').length, 0); -}); \ No newline at end of file +}); + +test('it rejects improper filetypes', function(assert) { + assert.expect(2); + + const component = this.subject({ + accept: '.jpg,.jpeg', + multiple: true + }); + + const files = [ + { filename: 'goodfile.jpg' }, + { filename: 'good_file.jpeg' }, + { filename: 'badfile.html' } + ]; + + assert.strictEqual(component._invalidExtension(files), true); + assert.strictEqual(component._invalidExtension(files.slice(0, 2)), false); +});