-1

I want to upload JSON file using only vanilla JavaScript on my website.

Whatever this code does with images, I need to do the same thing with a JSON file.

But changing the type to file type to JSON is not working, also the upload window automatically opens and only searches 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>&nbsp; Choose Or Drop Photos
      </label>
      <div id="error"></div>
      <div id="image-display"></div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>
  • It is unclear to me what you actually trying to achieve. With your broad description I seriously doubt that you actually want to "upload" a JSON. Do you want to POST a JSON to a web service or do you want to just display a JSON file on the screen? – tacoshy Aug 11 '23 at 06:03
  • @tacoshy In the code I have given they are uploading image, instead of an image I want to upload a JSON File – Jake Turner Aug 11 '23 at 06:16
  • @tacoshy just display JSON file on the screen on uploading. I'm trying to understand the code that is needed for upload function in JS. – Jake Turner Aug 11 '23 at 06:19
  • the code you provided does not upload an image. it just opens a file browser and allows you to display an image. Uploading something is to use something as method POST to upload to a server – tacoshy Aug 11 '23 at 06:20
  • if you want to upload a file, your `fileHandler` function will need to use some form of network request ... `XMLHttpRequest` or `fetch` being the two options in a browser – Jaromanda X Aug 11 '23 at 06:24
  • Where do you want up upload the JSON file to? Browser based javascript has no read/write access to the server for very good reason. You will need some form of serverside scripting to handle the JSON upload. – Jon P Aug 11 '23 at 06:24
  • @JonP upload nowhere, just from the computer to the website and display the JSON file. All frontend no need of HTTP requests or servers. I have added a sample program in the question. Whatever it does with image I need to do it with JSON. Please run that html code I have added in the question and see. – Jake Turner Aug 11 '23 at 06:41
  • @JaromandaX upload nowhere, just from the computer to the website and display the JSON file. All frontend no need of HTTP requests or servers. I have added a sample program in the question. Whatever it does with image I need to do it with JSON. Please run that html code I have added in the question and see. – Jake Turner Aug 11 '23 at 06:42
  • oh ... the issue is `fileHandler` only accepts `image` types ... you need to change it so it accepts text files - and also `accept="image/*"` change that, maybe `application/json`? - but how do you want to display the JSON? nicely indented multi-line? or as-is from the file? – Jaromanda X Aug 11 '23 at 06:43
  • If you're uploading to nowhere, then it isn't really an [upload](https://dictionary.cambridge.org/dictionary/english/upload). Hence the confusion. You're really opening/displaying a local JSON file in the browser. An upload would be loading/posting the file to the server. – Jon P Aug 11 '23 at 07:10
  • @JaromandaX thanks. I want to display the JSON as key value pairs. – Jake Turner Aug 11 '23 at 08:47
  • but JSON can be a lot more than that! – Jaromanda X Aug 11 '23 at 08:48
  • @JonP ohhh ok. Thanks for clarifying. I just want to display it from the file explorer to the website. – Jake Turner Aug 11 '23 at 08:48

0 Answers0