Skip to content

Commit

Permalink
fix: cherry-pick from 5652 to v23.3 (#5661) (#5663)
Browse files Browse the repository at this point in the history
Co-authored-by: Ugur Saglam <106508695+ugur-vaadin@users.noreply.github.com>
  • Loading branch information
vaadin-bot and ugur-vaadin committed Mar 14, 2023
1 parent aa60c43 commit 4c37764
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
28 changes: 22 additions & 6 deletions packages/upload/src/vaadin-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,26 @@ class Upload extends ElementMixin(ThemableMixin(PolymerElement)) {
};
}

/** @private */
get __acceptRegexp() {
if (!this.accept) {
return null;
}
const processedTokens = this.accept.split(',').map((token) => {
let processedToken = token.trim();
// Escape regex operators common to mime types
processedToken = processedToken.replace(/[+.]/g, '\\$&');
// Make extension patterns match the end of the file name
if (processedToken.startsWith('\\.')) {
processedToken = `.*${processedToken}$`;
}
// Handle star (*) wildcards
return processedToken.replace(/\/\*/g, '/.*');
});
// Create accept regex
return new RegExp(`^(${processedTokens.join('|')})$`, 'i');
}

/** @protected */
ready() {
super.ready();
Expand Down Expand Up @@ -779,12 +799,8 @@ class Upload extends ElementMixin(ThemableMixin(PolymerElement)) {
);
return;
}
const fileExt = file.name.match(/\.[^.]*$|$/)[0];
// Escape regex operators common to mime types
const escapedAccept = this.accept.replace(/[+.]/g, '\\$&');
// Create accept regex that can match comma separated patterns, star (*) wildcards
const re = new RegExp(`^(${escapedAccept.replace(/[, ]+/g, '|').replace(/\/\*/g, '/.*')})$`, 'i');
if (this.accept && !(re.test(file.type) || re.test(fileExt))) {
const re = this.__acceptRegexp;
if (re && !(re.test(file.type) || re.test(file.name))) {
this.dispatchEvent(
new CustomEvent('file-reject', {
detail: { file, error: this.i18n.error.incorrectFileType },
Expand Down
14 changes: 14 additions & 0 deletions packages/upload/test/adding-files.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,20 @@ describe('file list', () => {
expect(upload.files.length).to.equal(1);
});

it('should allow files with extensions containing multiple dots', () => {
upload.accept = 'image/*,.bar.baz,video/*';
file.name = 'foo.bar.baz';
upload._addFiles([file]);
expect(upload.files).to.have.lengthOf(1);
});

it('should reject files that have partial extension match', () => {
upload.accept = 'image/*,.bar.baz,video/*';
file.name = 'foo.baz';
upload._addFiles([file]);
expect(upload.files).to.have.lengthOf(0);
});

it('should allow files with correct mime type', () => {
upload.accept = 'application/x-octet-stream';
upload._addFiles([file]);
Expand Down

0 comments on commit 4c37764

Please sign in to comment.