Skip to content

Instantly share code, notes, and snippets.

@chege-kimaru
Created May 17, 2020 19:41
Show Gist options
  • Save chege-kimaru/b2292d0fec923a1812076d9ecb274595 to your computer and use it in GitHub Desktop.
Save chege-kimaru/b2292d0fec923a1812076d9ecb274595 to your computer and use it in GitHub Desktop.
A sample code on how to upload a file without using form input
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Uploader</title>
<style>
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.box {
position: relative;
width: 50%;
height: 400px;
border-radius: 5px;
box-shadow: 2px 6px 15px 0 rgba(69, 65, 78, 0.1);
}
.images {
height: 400px;
bottom: 40px;
overflow-y: auto;
}
.images img {
width: 100px;
height: 70px;
border-radius: 5px;
object-fit: cover;
margin: 5px;
}
.button {
position: absolute;
bottom: 0;
width: 100%;
padding-top: 10px;
padding-bottom: 10px;
background-color: #0c5460;
color: #fff;
border-radius: 5px;
vertical-align: middle;
text-align: center;
font-weight: 600;
font-family: "Helvetica Neue", sans-serif;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<div class="box">
<div class="images">
</div>
<div class="button">
Add Image
</div>
</div>
</div>
<script>
const button = document.querySelector('.button');
const imagesContainer = document.querySelector('.images');
button.addEventListener('click', async () => {
const files = await selectFile('image/*', true);
onFileSelected(files);
});
const addImage = (src) => {
const img = document.createElement('img');
img.setAttribute('src', src);
imagesContainer.appendChild(img);
};
const onFileSelected = (files) => {
for (const file of files) {
if (typeof (FileReader) !== 'undefined') {
const reader = new FileReader();
reader.onload = (e) => {
if (typeof reader.result === 'string') {
addImage(reader.result)
}
};
reader.readAsDataURL(file);
}
}
};
const selectFile = (contentType, multiple) => {
return new Promise(resolve => {
const input = document.createElement('input');
input.type = 'file';
input.multiple = multiple;
input.accept = contentType;
input.onchange = () => {
const files = Array.from(input.files);
// if (multiple) {
// resolve(files);
// } else {
// resolve(files[0]);
// }
resolve(files);
};
input.click();
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment