Search code examples
gatsbynetlify

How to handle file uploads in a `gatsby js` project?


There is an excellent article explain how to handle form submission in a Gatsby Js project hosted on netlify. However it's only about text values submission, how about the form includes some file inputs?

Any one can shed some light here?


Solution

  • Thanks for @coreyward's help. That I figured out the problem here is how to use javascript fetch API to post a form data. So the solution here is quite straightforward:

    const encode = (data) => {
      const formData = new FormData()
      Object.keys(data)
        .map(key => {
          if (key === 'files') {
            for (const file of data[key]) {
              formData.append(key, file, file.name)
            }
          } else {
            formData.append(key, data[key])
          }
        })
      return formData
    }
    
    await window.fetch('/', {
        method: 'POST',
        body: encode({ 'form-name': 'loan', ...this.state, userId: netlifyIdentity.currentUser().id }),
      })
    

    You can notice that the only tricky part is rewrite the encode function of the official sample article from uri encoding to form data encoding.