Created
June 9, 2020 18:58
-
-
Save thehackermonkey/77cbd73922bec41ad537bb10b9eb0232 to your computer and use it in GitHub Desktop.
Ejemplo de subida de una imagen a través de una url pre firmada por el backend usando reactjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useState, useEffect} from 'react'; | |
import axios from 'axios'; | |
export default function imagesUpload() { | |
const [file, setFile] = useState(); | |
const [awsUrl, setAwsUrl] = useState(null); | |
useEffect(() => { | |
axios.get('http://localhost:3001/presignedUrl') | |
.then(r => setAwsUrl(r.data)) | |
.catch(err => console.log(err)); | |
}, []); | |
useEffect(() => { | |
if (file) { | |
const formData = new FormData(); | |
formData.append('file', file); | |
fetch(awsUrl.full, { | |
method: 'PUT', | |
body: file | |
}) | |
.then( | |
response => console.log(response) // if the response is a JSON object | |
).then( | |
success => console.log(success) // Handle the success response object | |
).catch( | |
error => console.log(error) // Handle the error response object | |
); | |
} | |
}, [file]); | |
return ( | |
<div> | |
<input type="file" | |
onChange={e => setFile(e.target.files[0])} | |
id="file-upload" name="avatar" | |
accept="image/png, image/jpeg, image/gif" /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment