Check if a file exists locally using JavaScript only

后端 未结 10 1640
盖世英雄少女心
盖世英雄少女心 2020-12-03 14:01

I want to check if a file exists locally, where the HTML file is located. It has to be JavaScript. JavaScript will never be disabled. jQuery is not good but can do.

相关标签:
10条回答
  • 2020-12-03 14:34

    Fortunately, it's not possible (for security reasons) to access client-side filesystem with standard JS. Some proprietary solutions exist though (like Microsoft's IE-only ActiveX component).

    0 讨论(0)
  • 2020-12-03 14:36

    One way I've found to do this is to create an img tag and set the src attribute to the file you are looking for. The onload or onerror of the img element will fire based on whether the file exists. You can't load any data using this method, but you can determine if a particular file exists or not.

    0 讨论(0)
  • 2020-12-03 14:37

    No need for an external library if you use Nodejs all you need to do is import the file system module. feel free to edit the code below: const fs = require('fs')

    const path = './file.txt'
    
    fs.access(path, fs.F_OK, (err) => {
      if (err) {
        console.error(err)
        return
      }
    
      //file exists
    })
    
    0 讨论(0)
  • 2020-12-03 14:42

    Try this:

    window.onclick=(function(){
      try {
        var file = window.open("file://mnt/sdcard/download/Click.ogg");
        setTimeout('file.close()', 100);
        setTimeout("alert('Audio file found. Have a nice day!');", 101);
      } catch(err) {
        var wantstodl=confirm("Warning:\n the file, Click.ogg is not found.\n do you want to download it?\n "+err.message);
        if (wantstodl) {
          window.open("https://www.dropbox.com/s/qs9v6g2vru32xoe/Click.ogg?dl=1"); //downloads the audio file
        }
      }
    });
    
    0 讨论(0)
提交回复
热议问题