0

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.

rico_mac
  • 810
  • 6
  • 21
  • See https://stackoverflow.com/questions/47164372/prevent-redirect-on-file-upload-through-form-submittal-react-express-multer/47183642#47183642 for how I handle uploading files in React – Joshua Underwood Nov 08 '17 at 15:34

2 Answers2

2

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.

Tim Brayshaw
  • 412
  • 3
  • 8
1

the easiest way to tackle this is to use an input of type file, eg.

<input type="file" onChange={yourChangeHandler}/>

and the corresponding event handler function as follows:

function yourChangeHandler(event){
  let yourfile = event.target.files; 
}

I've managed to store this in a FormData object and sent it using axios with no problems at all