Skip to content

Instantly share code, notes, and snippets.

@Faliszek
Created February 11, 2022 16:33
Show Gist options
  • Save Faliszek/73db9aa9fc1e26599a05bc58e4da5a58 to your computer and use it in GitHub Desktop.
Save Faliszek/73db9aa9fc1e26599a05bc58e4da5a58 to your computer and use it in GitHub Desktop.
import { useState } from 'react';
function SimpleReactFileUpload() {
const [file, setFile] = useState(null);
function onChange(e) {
setFile(e.target.files[0])
}
function fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return fetch(url, {method: "POST", body: formData, headers: headers})
}
function onFormSubmit(e){
e.preventDefault()
fileUpload(file).then((response)=>{
console.log(response.data);
})
}
return (
<form onSubmit={onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={onChange} />
<button type="submit">Upload</button>
</form>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment