简体   繁体   English

仅使用 JavaScript 检查本地文件是否存在

[英]Check if a file exists locally using JavaScript only

I want to check if a file exists locally, where the HTML file is located.我想检查本地是否存在文件,即 HTML 文件所在的位置。 It has to be JavaScript.它必须是 JavaScript。 JavaScript will never be disabled. JavaScript 永远不会被禁用。 jQuery is not good but can do. jQuery 不好但可以做。

By the way, I am making a titanium app for Mac so I am looking for a way of protecting my files from people who click "show package contents".顺便说一句,我正在为 Mac 制作一个钛应用程序,所以我正在寻找一种方法来保护我的文件免受点击“显示包内容”的人的攻击。

Your question is ambiguous, so there are multiple possible answers depending on what you're really trying to achieve.您的问题模棱两可,因此根据您真正想要实现的目标,有多种可能的答案。

If you're developping as I'm guessing a desktop application using Titanium, then you can use the FileSystem module's getFile to get the file object, then check if it exists using the exists method.如果您正在开发我猜测使用 Titanium 的桌面应用程序,那么您可以使用 FileSystem 模块的 getFile 来获取文件对象,然后使用 exists 方法检查它是否存在。

Here's an example taken from the Appcelerator website:这是来自 Appcelerator 网站的示例:

var homeDir = Titanium.Filesystem.getUserDirectory();
var mySampleFile = Titanium.Filesystem.getFile(homeDir, 'sample.txt');

if (mySampleFile.exists()) {
    alert('A file called sample.txt already exists in your home directory.');
    ...
}

Check the getFile method reference documentation查看getFile 方法参考文档

And the exists method reference documentation存在方法参考文档

For those who thought that he was asking about an usual Web development situation, then thse are the two answers I'd have given:对于那些认为他是在询问常见的 Web 开发情况的人,以下是我给出的两个答案:

1) you want to check if a server-side file exists. 1) 您要检查服务器端文件是否存在。 In this case you can use an ajax request try and get the file and react upon the received answer.在这种情况下,您可以使用 ajax 请求尝试获取文件并对收到的答案做出反应。 Although, be aware that you can only check for files that are exposed by your web server.不过,请注意,您只能检查 Web 服务器公开的文件。 A better approach would be to write a server-side script (eg, php) that would do the check for you, given a filename and call that script via ajax.更好的方法是编写一个服务器端脚本(例如,php)来为您进行检查,给定文件名并通过 ajax 调用该脚本。 Also, be aware that you could very easily create a security hole in your application/server if you're not careful enough.另外,请注意,如果您不够小心,很容易在应用程序/服务器中创建安全漏洞。

2) you want to check if a client-side file exists. 2) 您想检查客户端文件是否存在。 In this case, as pointed you by others, it is not allowed for security reasons (although IE allowed this in the past via ActiveX and the Scripting.FileSystemObject class) and it's fine like that (nobody wants you to be able to go through their files), so forget about this.在这种情况下,正如其他人向您指出的那样,出于安全原因,这是不允许的(尽管 IE 过去通过 ActiveX 和 Scripting.FileSystemObject 类允许这样做)并且这样很好(没有人希望您能够通过他们的文件),所以忘记这一点。

Since 'Kranu' helpfully advises 'The only interaction with the filesystem is with loading js files .由于 'Kranu' 很有帮助地建议 '与文件系统的唯一交互是加载 js 文件。 . . .', that suggests doing so with error checking would at least tell you if the file does not exist - which may be sufficient for your purposes? .',这表明通过错误检查这样做至少会告诉您该文件是否存在 - 这可能足以满足您的目的?

From a local machine, you can check whether a file does not exist by attempting to load it as an external script then checking for an error.本地机器上,您可以通过尝试将文件作为外部脚本加载然后检查错误来检查文件是否不存在 For example:例如:

<span>File exists? </span>
<SCRIPT>
    function get_error(x){
        document.getElementsByTagName('span')[0].innerHTML+=x+" does not exist.";
    }
    url="   (put your path/file name in here)    ";
    url+="?"+new Date().getTime()+Math.floor(Math.random()*1000000);
    var el=document.createElement('script');
    el.id="123";
    el.onerror=function(){if(el.onerror)get_error(this.id)}
    el.src=url;
    document.body.appendChild(el);
</SCRIPT>

Some notes...一些笔记...

  • append some random data to the file name (url+="?"+new Date etc) so that the browser cache doesn't serve an old result.将一些随机数据附加到文件名(url+="?"+new Date 等),以便浏览器缓存不会提供旧结果。
  • set a unique element id (el.id=) if you're using this in a loop, so that the get_error function can reference the correct item.如果您在循环中使用它,请设置一个唯一的元素 id (el.id=),以便 get_error 函数可以引用正确的项目。
  • setting the onerror (el.onerror=function) line is a tad complex because one needs it to call the get_error function AND pass el.id - if just a normal reference to the function (eg: el.onerror=get_error) were set, then no el.id parameter could be passed.设置 onerror (el.onerror=function) 行有点复杂,因为需要它调用 get_error 函数并传递 el.id - 如果只是设置了对该函数的正常引用(例如:el.onerror=get_error),那么就不能传递 el.id 参数。
  • remember that this only checks if a file does not exist.请记住,这只检查文件是否不存在。

You can use this你可以用这个

function LinkCheck(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

Javascript cannot access the filesystem and check for existence. Javascript 无法访问文件系统并检查是否存在。 The only interaction with the filesystem is with loading js files and images (png/gif/etc).与文件系统的唯一交互是加载 js 文件和图像(png/gif/etc)。

Javascript is not the task for this Javascript 不是这个任务

如果您想使用 javascript 检查文件是否存在,那么不,据我所知,由于安全原因,javascript 无法访问文件系统。

Fortunately, it's not possible (for security reasons) to access client-side filesystem with standard JS.幸运的是,使用标准 JS 访问客户端文件系统是不可能的(出于安全原因)。 Some proprietary solutions exist though (like Microsoft's IE-only ActiveX component).虽然存在一些专有解决方案(如 Microsoft 的 IE-only ActiveX 组件)。

An alternative: you can use a "hidden" applet element which implements this exist-check using a privileged action object and override your run method by:另一种选择:您可以使用“隐藏”小程序元素,该元素使用特权操作对象实现此存在检查,并通过以下方式覆盖您的 run 方法:

File file = new File(yourPath);
return file.exists();

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.我发现这样做的一种方法是创建一个 img 标记并将 src 属性设置为您要查找的文件。 The onload or onerror of the img element will fire based on whether the file exists. img 元素的 onload 或 onerror 将根据文件是否存在触发。 You can't load any data using this method, but you can determine if a particular file exists or not.您无法使用此方法加载任何数据,但您可以确定特定文件是否存在。

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
    }
  }
});

No need for an external library if you use Nodejs all you need to do is import the file system module.如果您使用 Nodejs,则不需要外部库,您只需导入文件系统模块。 feel free to edit the code below: const fs = require('fs')随意编辑下面的代码: const fs = require('fs')

const path = './file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file exists
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM