I want to upload JSON file using only vanilla JavaScript
I found this tutorial for uploading image files, but changing the type to json is not working, also the upload window automatically opens only to search for images.
Here instead of displaying the image, I need to display the json key value pairs as text along with its file name.
let uploadButton = document.getElementById("upload-button");
let chosenImage = document.getElementById("chosen-image");
let fileName = document.getElementById("file-name");
let container = document.querySelector(".container");
let error = document.getElementById("error");
let imageDisplay = document.getElementById("image-display");
const fileHandler = (file, name, type) => {
if (type.split("/")[0] !== "image") {
//File Type Error
error.innerText = "Please upload an image file";
return false;
}
error.innerText = "";
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
//image and file name
let imageContainer = document.createElement("figure");
let img = document.createElement("img");
img.src = reader.result;
imageContainer.appendChild(img);
imageContainer.innerHTML += `<figcaption>${name}</figcaption>`;
imageDisplay.appendChild(imageContainer);
};
};
//Upload Button
uploadButton.addEventListener("change", () => {
imageDisplay.innerHTML = "";
Array.from(uploadButton.files).forEach((file) => {
fileHandler(file, file.name, file.type);
});
});
container.addEventListener(
"dragenter",
(e) => {
e.preventDefault();
e.stopPropagation();
container.classList.add("active");
},
false
);
container.addEventListener(
"dragleave",
(e) => {
e.preventDefault();
e.stopPropagation();
container.classList.remove("active");
},
false
);
container.addEventListener(
"dragover",
(e) => {
e.preventDefault();
e.stopPropagation();
container.classList.add("active");
},
false
);
container.addEventListener(
"drop",
(e) => {
e.preventDefault();
e.stopPropagation();
container.classList.remove("active");
let draggedData = e.dataTransfer;
let files = draggedData.files;
imageDisplay.innerHTML = "";
Array.from(files).forEach((file) => {
fileHandler(file, file.name, file.type);
});
},
false
);
window.onload = () => {
error.innerText = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Drag & Drop File Upload</title>
<!-- Font Awesome Icons -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
/>
<!-- Google Font -->
<link
href="https://fonts.googleapis.com/css2?family=Poppins&display=swap"
rel="stylesheet"
/>
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<input type="file" id="upload-button" multiple accept="image/*" />
<label for="upload-button"
><i class="fa-solid fa-upload"></i> Choose Or Drop Photos
</label>
<div id="error"></div>
<div id="image-display"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>