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

时间:2022-02-04 23:49:16

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.

我想检查HTML文件所在的本地文件是否存在。它必须是JavaScript。永远不会禁用JavaScript。 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制作一个钛应用程序,所以我正在寻找一种方法来保护我的文件免受点击“显示包内容”的人的影响。

9 个解决方案

#1


15  

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. In this case you can use an ajax request try and get the file and react upon the received answer. Although, be aware that you can only check for files that are exposed by your web server. A better approach would be to write a server-side script (e.g., php) that would do the check for you, given a filename and call that script via ajax. Also, be aware that you could very easily create a security hole in your application/server if you're not careful enough.

1)您要检查服务器端文件是否存在。在这种情况下,您可以使用ajax请求尝试获取文件并对收到的答案做出反应。但请注意,您只能检查Web服务器公开的文件。一个更好的方法是编写一个服务器端脚本(例如,php),它将为你做检查,给定一个文件名并通过ajax调用该脚本。另外,请注意,如果您不够小心,可以在应用程序/服务器中轻松创建安全漏洞。

2) you want to check if a client-side file exists. 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.

2)您要检查是否存在客户端文件。在这种情况下,正如其他人所指出的那样,出于安全原因不允许这样做(虽然IE过去通过ActiveX和Scripting.FileSystemObject类允许这样做)并且它很好(没人希望你能够通过他们的文件),所以忘记这一点。

#2


10  

Since 'Kranu' helpfully advises 'The only interaction with the filesystem is with loading js files . . .', 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?

由于'Kranu'有用地建议'与文件系统的唯一交互是加载js文件。 。 。',这表明通过错误检查这样做至少会告诉你文件是否不存在 - 这可能足以满足您的目的?

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 etc),以便浏览器缓存不会提供旧的结果。

  • 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.
  • 请记住,这只会检查文件是否不存在。

#3


8  

You can use this

你可以用它

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

#4


4  

Javascript cannot access the filesystem and check for existence. The only interaction with the filesystem is with loading js files and images (png/gif/etc).

Javascript无法访问文件系统并检查是否存在。与文件系统的唯一交互是加载js文件和图像(png / gif / etc)。

Javascript is not the task for this

Javascript不是这个的任务

#5


3  

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).

幸运的是,由于安全原因,使用标准JS访问客户端文件系统是不可能的。但是存在一些专有解决方案(如Microsoft的IE-only ActiveX组件)。

#6


3  

If you want to check if file exists using javascript then no, as far as I know, javascript has no access to file system due to security reasons.. But as for me it is not clear enough what are you trying to do..

如果你想使用javascript检查文件是否存在那么没有,据我所知,由于安全原因,javascript无法访问文件系统..但至于我还不清楚你想要做什么...

#7


2  

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:

另一种方法是:您可以使用“隐藏”的applet元素,该元素使用特权操作对象实现此存在检查,并通过以下方式覆盖您的run方法:

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

#8


1  

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.

我发现这样做的一种方法是创建一个img标记并将src属性设置为您要查找的文件。 img元素的onload或onerror将根据文件是否存在而触发。您无法使用此方法加载任何数据,但可以确定是否存在特定文件。

#9


0  

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

#1


15  

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. In this case you can use an ajax request try and get the file and react upon the received answer. Although, be aware that you can only check for files that are exposed by your web server. A better approach would be to write a server-side script (e.g., php) that would do the check for you, given a filename and call that script via ajax. Also, be aware that you could very easily create a security hole in your application/server if you're not careful enough.

1)您要检查服务器端文件是否存在。在这种情况下,您可以使用ajax请求尝试获取文件并对收到的答案做出反应。但请注意,您只能检查Web服务器公开的文件。一个更好的方法是编写一个服务器端脚本(例如,php),它将为你做检查,给定一个文件名并通过ajax调用该脚本。另外,请注意,如果您不够小心,可以在应用程序/服务器中轻松创建安全漏洞。

2) you want to check if a client-side file exists. 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.

2)您要检查是否存在客户端文件。在这种情况下,正如其他人所指出的那样,出于安全原因不允许这样做(虽然IE过去通过ActiveX和Scripting.FileSystemObject类允许这样做)并且它很好(没人希望你能够通过他们的文件),所以忘记这一点。

#2


10  

Since 'Kranu' helpfully advises 'The only interaction with the filesystem is with loading js files . . .', 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?

由于'Kranu'有用地建议'与文件系统的唯一交互是加载js文件。 。 。',这表明通过错误检查这样做至少会告诉你文件是否不存在 - 这可能足以满足您的目的?

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 etc),以便浏览器缓存不会提供旧的结果。

  • 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.
  • 请记住,这只会检查文件是否不存在。

#3


8  

You can use this

你可以用它

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

#4


4  

Javascript cannot access the filesystem and check for existence. The only interaction with the filesystem is with loading js files and images (png/gif/etc).

Javascript无法访问文件系统并检查是否存在。与文件系统的唯一交互是加载js文件和图像(png / gif / etc)。

Javascript is not the task for this

Javascript不是这个的任务

#5


3  

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).

幸运的是,由于安全原因,使用标准JS访问客户端文件系统是不可能的。但是存在一些专有解决方案(如Microsoft的IE-only ActiveX组件)。

#6


3  

If you want to check if file exists using javascript then no, as far as I know, javascript has no access to file system due to security reasons.. But as for me it is not clear enough what are you trying to do..

如果你想使用javascript检查文件是否存在那么没有,据我所知,由于安全原因,javascript无法访问文件系统..但至于我还不清楚你想要做什么...

#7


2  

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:

另一种方法是:您可以使用“隐藏”的applet元素,该元素使用特权操作对象实现此存在检查,并通过以下方式覆盖您的run方法:

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

#8


1  

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.

我发现这样做的一种方法是创建一个img标记并将src属性设置为您要查找的文件。 img元素的onload或onerror将根据文件是否存在而触发。您无法使用此方法加载任何数据,但可以确定是否存在特定文件。

#9


0  

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