ruby-on-railsreactjsformsy-react

React simple form file upload


I am writing out a form as a React component. I am able to successfully post/patch form data to my server (Rails 5 API). However, I am struggling to see how I attach a file to the payload.

With my current file upload implementation, when the form is posted to the server the params look like this:

  Parameters: {"theme"=>{"slug"=>"sonair", ... "primary_asset_attachment"=>{"0"=>{}}}, "theme_id"=>"sonair"}

My expectation was the primary_asset_attachment would contain a reference to the file.

    <FRC.Form
      onSubmit         =   { this.submitForm }
      validationErrors =   { this.state.validationErrors } >

      .... contents elided ....

      <File
        name           =   "primary_asset_attachment"
        label          =   "Theme Image"
        help           =   "Please attach an image"
      />
    </FRC.Form>

I am using a React plugin called Formsy, if this helps.

There are obviously some fairly critical steps I am missing.


Solution

  • the <File /> component is very similar to the other <Input /> components, but instead of returning the input element's value (which contains a fake path for security reasons), it returns a HTML5 FileList as the component's value.

    To upload this data, use FormData.append and then upload using XMLHttpRequest or fetch.