Skip to content

Commit

Permalink
[FEATURE] Uses accept field to validate provided filetypes
Browse files Browse the repository at this point in the history
  • Loading branch information
timmcanty committed Apr 19, 2016
1 parent 17826d3 commit 46a69a0
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
29 changes: 28 additions & 1 deletion addon/components/file-picker.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export default Component.extend({
dropzone: true,
progress: true,
showProgress: false,
validateExtension: true,
hideFileInput: true,
readAs: 'readAsFile',
selectOnClick: true,
Expand Down Expand Up @@ -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);
}
Expand Down
20 changes: 19 additions & 1 deletion tests/unit/components/file-picker-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,22 @@ test('it shows file input', function(assert) {
this.render();

assert.equal(component.$('input:hidden').length, 0);
});
});

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);
});

0 comments on commit 46a69a0

Please sign in to comment.