jhpyle / docassemble

A free, open-source expert system for guided interviews and document assembly, based on Python, YAML, and Markdown.
https://docassemble.org
MIT License
769 stars 252 forks source link

File upload field not recognising correct filetype with 'accept' specifier #149

Closed lordenaar closed 2 years ago

lordenaar commented 5 years ago

When using the 'accept' specifier in a file upload field, the browser recognises the accepted file extension, and other extensions are not permitted to be selected. When a correct filetype is selected, "Please upload a file with a valid file format." is displayed upon pressing continue.

The following question demonstrates the error (for DRF files):

mandatory: true
question: Upload a .drf file
fields:
  - File: new_file
    datatype: file
    accept: |
      '.drf'
---

Giving a single string specifier as per the Mozilla page referenced in the DA documentation:

A valid case-insensitive filename extension, starting with a period (".") character. For example: .jpg, .pdf, or .doc.

Using Google Chrome Version 73.0.3683.103 (64 bit)

jhpyle commented 5 years ago

This seems to be a limitation of the JQuery Validation Plugin. It automatically process the "accept" attribute and displays an error message if the file doesn't match. It works with MIME types but doesn't seem to work with file extensions.

https://jqueryvalidation.org/accept-method/

jhpyle commented 5 years ago

It looks like they are working on the problem over at jquery-validation:

https://github.com/jquery-validation/jquery-validation/issues/2271

In any case, see https://docassemble.org/docs/recipes.html#upload%20validation for an example of validating file uploads on the server. In your case you could do:

question: |
  Please upload a file.
fields:
  File: uploaded_file
  datatype: file
validation code: |
  for the_file in uploaded_file:
    if the_file.extension != 'drf':
      validation_error("You can only upload a .drf file.")

You could also take this opportunity to test the .drf file for validity. You could try to open it while wrapping your code in try/except, and if there is an error, call validation_error("Please upload a valid DRF file.").

jhpyle commented 2 years ago

I am going through old issues to close them out. I have been keeping jquery-validation updated and they closed the issue I linked to above. So I am closing this for now. It can be reopened if there are further issues.