71

Posting a file using the fetch API

 5 years ago
source link: https://www.tuicool.com/articles/hit/QFbMj2e
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Posting a file using the fetch API

  • Time-stamp: <2018-11-06 13:37:57 tamara>
  • published date: [2018-11-06 Tue 13:17]
  • keywords: javascript, fetch, file upload

I’m investigating this for work

See MDN: Uploading a file (fetch)

Files can be uploaded using an HTML <input type=”file” /> input element, FormData() and fetch().
let formData = new FormData();

const fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');

// file fields provide a collection of files, apparently.
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
    method: 'PUT',
    headers: {
        'Content-type': 'application/x-www-form-urlencoded'
    },
    body: formData,
})
    .then(response => response.json())
    .catch(error => console.error('Error:', error))
    .then(response => console.log('Success:', JSON.stringify(response)));

In a React context, the information would be obtained using a React `ref` instead of the POJS `querySelector`, but it ends up close to the same afterwards:

fileFieldRef = React.createRef()

handleSubmit = () => {
    let formData = new FormData()
    const fileField = this.fileFieldRef.current

    formData.append('username', 'abc123')
    formData.append('avatar', fileField.files[0])

    fetch('https://example.com/profile/avatar', {
        method: 'PUT',
        headers: {
            'Content-type': 'application/x-www-form-urlencoded'
        },
        body: formData,
    })
        .then(response => response.json())
        .catch(error => console.error('Error:', error))
        .then(response => console.log('Success:', JSON.stringify(response)));
}

// ...

render() {
    return (
        <form onSubmit={this.handleSubmit}>
          <input type="file" ref={this.fileFieldRef}/>
        </form>
    )
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK