rico_mac
rico_mac

Reputation: 888

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.

Upvotes: 0

Views: 1197

Answers (2)

William Alagaratnam
William Alagaratnam

Reputation: 241

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

Upvotes: 1

Tim Brayshaw
Tim Brayshaw

Reputation: 512

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.

Upvotes: 2

Related Questions