Skip to content

Client side FileField Enhancements

Jonathan Buchanan edited this page Apr 9, 2014 · 4 revisions

(Hypothetical APIs below)

onChange handler

Accept an onChange handler and hook it up to the file input widget, passing the original event so the user can handle the actual file uploading. This hook should be all that's needed for non-required file fields - you handle everything else yourself:

forms.ImageField({onChange: this.handleScreenshotUpload})

Configurable onChange validation

Provide handling for common validation using the File API when available: e.g. file size and type. In this case the Form or Field would provide its own onChange handler and the user's own onChange handler would be called with the event only when configured validation passes:

forms.ImageFIeld({onChange: this.handleScreenshotUpload, maxSize: '2MB', accept: ['png', 'jpg']})
forms.FileField({onChange: this.handleZipUpload, maxSize: '10MB', accept: ['zip', '7z']}

There are already special-case flags on Widgets for FileFields - this would also be special-case validation at the Field level, as it's validating an event rather than user input from form.data.

Required FileFields

  • the user would need to pass some initial data indicating if an uploaded file already exists
  • the Field and its Widget would need to manage some state indicating whether or not a new file has been uploaded - this could be a controlled, hidden field with a unique prefix
  • need to provide a way for the user to update this managed state from their onChange handler
    • uploading will be asynchronous if people value their users' experience, so an additional callback passed to the handler alongside the event makes sense
      • callback with a ValidationError if the file is invalid

(Later) Multi-file upload

(Haven't thought this one through much yet)

Users can currently add multiple to the file input themselves:

forms.FileField({
  onChange: this.handleUpload
, widget: forms.FileInput({attrs: {multiple: 'multiple'}})
})
  • Should multiple be pulled up to the Field level to make it more convenient?
  • Should MultipleFileField and MultipleImageField be created instead?
    • Same client side validation logic, but in a loop before calling user's onChange
    • Server-side logic would need to handle receiving a list of files in order to preserve continued server-only usage of newforms.
    • "Interesting" scenarios in terms of partial success? Some files valid, some invalid? Calling back with both error and result populated!