Skip to content

Instantly share code, notes, and snippets.

@emersonbrogadev
Last active April 2, 2023 15:18
Show Gist options
  • Save emersonbrogadev/e9de58950d2efbaca5a4b84515d01afe to your computer and use it in GitHub Desktop.
Save emersonbrogadev/e9de58950d2efbaca5a4b84515d01afe to your computer and use it in GitHub Desktop.
Upload de imagens com a FETCH API do JavaScript!
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<h1>Upload!</h1>
<form id="upload-form" action="" method="post">
<input type="file" name="file" id="file">
<input type="submit" value="Upload image" name="submit">
</form>
<div id="gallery">
<!-- images -->
</div>
<script type="text/javascript">
const CLIENT_ID = '';
const gallery = document.getElementById('gallery');
const doUpload = (url, options) => {
const promiseCallback = (resolve, reject) => {
const getFetchJson = (response) => {
if(!response.ok) return reject(response);
return response.json().then(resolve);
}
fetch(url, options)
.then(getFetchJson)
.catch(reject);
};
return new Promise(promiseCallback);
};
const addImage = (url) => {
gallery.innerHTML += `<img src="${url}" width="300" />`;
}
const onSuccess = (result) => {
const { data: { link } } = result;
addImage(link);
};
const uploadImage = (e) => {
e.preventDefault();
const file = document.getElementById('file');
const data = new FormData();
data.append('image', file.files[0]);
doUpload('https://api.imgur.com/3/image', {
method: 'POST',
body: data,
headers: {
'Authorization': `Client-ID ${CLIENT_ID}`,
}
})
.then(onSuccess)
.catch(console.error);
}
const form = document.getElementById('upload-form');
form.addEventListener('submit', uploadImage)
</script>
</body>
</html>
@rudilp28
Copy link

Boa noite , eu fiz conforme o video e estou com problemas esta dando erro no GET 403 e vem essa mensagem =>

A cookie associated with a cross-site resource at http://imgur.com/ was set without the SameSite attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

@rudilp28
Copy link

se puder me ajudar eu agradeço!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment