Home > database >  How to get the file extension type of an uploaded file in Javascript
How to get the file extension type of an uploaded file in Javascript

Time:11-09

I've created a file upload system where the user can either upload an image or video. I then display a preview for the currently uploaded file.

Result desired: I want to display just **ONE **preview depending on the file type (image || video).

Question: How can I display just ONE preview depending on the file type?

Attempt: I've tried using '.split' && '.pop' to extract just the file extension but to no avail.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- <link rel="stylesheet"  href="/styles/style.css"> -->
    <link rel="stylesheet"  href="/styles/index.css">
</head>

<body id="upload_body">
    <!--File Upload -->
    <div >
        <div >

            <input type="file" id="file_picker" accept="image/*,video/mp4"><br>
            <div >
                     <!-- Show button if image is displayed-->
                     <button type="button" id="button_clear">CLEAR</button><br>
                     <!--Show image preview-->
                     <img id="image" src="" height="300px" width="auto"><br>
                    <!--Show video preview -->
                     <video id="video" src=""  height="300px" width="auto" autoplay="true" loop muted></video>
                 </div>
        </div>
        </div>
        <!-- Socials -->
        <h3 >
            Follow Us <br><br>
            <a href="https://twitter.com/DevTopia_">
                <img src="/assets/twitter.png" alt="twitter profile link" height="32px"/>
            </a>
            <a href="https://discord.gg/GAHDdWyj">
                <img src="/assets/discord.png" alt="twitter profile link" height="32px"/>
            </a>
        </h3>
    </div>
    <!-- JS -->
    <script type="application/javascript" src="/js/file_picker.js"></script>
    <script type="application/javascript" src="/js/content_script.js"></script>
</body>

</html>

Javascript

function storage_onChanged(changes, areaName) {
  let settings = {};
  if (areaName == "local") {
    if (changes.image_data_url) {
      settings.image_data_url = changes.image_data_url.newValue ?? "";
    }
    if (changes.image_filename) {
      settings.image_filename = changes.image_filename.newValue ?? "none";
    }
  }
  set_image(settings);
}

function set_image(settings) {
  let image = document.getElementById("image");
  let file_picker = document.getElementById("file_picker");
  let video = document.getElementById("video");
  let ext = file_picker.value.split(".").pop();

  if (settings.image_data_url !== undefined) {
    video.src = settings.image_data_url;
    image.src = settings.image_data_url;
  }
  if (settings.image_filename !== undefined) {
    image.alt = settings.image_filename;
    video.alt = settings.image_filename;
  }
}

function remove_image() {
  chrome.storage.local.remove(["image_data_url", "image_filename"]);
}

function store_image() {
  if (this.files.length > 0) {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      chrome.storage.local.set({
        image_data_url: reader.result,
        image_filename: this.files[0].name,
      });
    });
    reader.readAsDataURL(this.files[0]);
  }
}

// Initialization
chrome.storage.local.get(["image_data_url", "image_filename"]).then((items) => {
  set_image({
    image_data_url: items.image_data_url ?? "",
    image_filename: items.image_filename ?? "none",
  });
});
// File Picker
let file_picker = document.querySelector("#file_picker");
if (file_picker) {
  file_picker.addEventListener("change", store_image);
}
var button_clear = document.getElementById("button_clear");
if (button_clear) {
  button_clear.addEventListener("click", remove_image);
}

chrome.storage.onChanged.addListener(storage_onChanged);
// End

CodePudding user response:

The File object exposes a type property.

So you could choose how to display a preview based on the type:

document.querySelector('[type=file]').addEventListener('change', async (event) => {
  // get the first file
  const [file] = event.target.files;
  
  // get the preview
  const dataUrl = await preview(file);
  
  // choose what dom element type to create based on file.type
  // (i'm not sure you'd actually want to do precisely this.
  // just illustrating that you can do whatever you want with the type.)
  const previewType = file.type.startsWith('image') ? 'img' : 'video';
    
  // create the DOM element
  const previewElem = document.createElement(previewType);
  
  // set src to the preview
  previewElem.src = dataUrl;
  
  // add it to the document
  document.body.appendChild(previewElem);
})


// create a dataURL preview from the given file
async function preview(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      resolve(reader.result);
    });
    reader.readAsDataURL(file);
  })
}
<input type="file" />

  • Related