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

发布于 2024-10-19 07:33:58 字数 151 浏览 2 评论 0原文

我想检查 HTML 文件所在的本地是否存在文件。它必须是 JavaScript。 JavaScript 永远不会被禁用。 jQuery 不好但是可以。

顺便说一句,我正在为 Mac 制作一个钛应用程序,所以我正在寻找一种方法来保护我的文件免受单击“显示包内容”的人的影响。

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

游魂 2024-10-26 07:33:58

您的问题不明确,因此根据您真正想要实现的目标,有多种可能的答案。

如果您正在开发一个使用 Titanium 的桌面应用程序,那么您可以使用 FileSystem 模块的 getFile 来获取文件对象,然后使用 contains 方法检查它是否存在。

以下是来自 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.');
    ...
}

检查 getFile 方法参考文档

exists 方法参考文档

对于那些认为他问的是通常的 Web 开发情况的人,那么这是我给出的两个答案:

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

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

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.

Here's an example taken from the Appcelerator website:

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

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:

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.

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.

谢绝鈎搭 2024-10-26 07:33:58

因为“Kranu”建议“与文件系统的唯一交互是加载 js 文件”。 。 .',这表明通过错误检查来执行此操作至少会告诉您该文件是否存在 - 这可能足以满足您的目的?

本地计算机上,您可以通过尝试将文件作为外部脚本加载然后检查错误来检查文件是否不存在。例如:

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

一些注释...

  • 将一些随机数据附加到文件名(url + =“?”+新日期等),以便浏览器缓存不提供旧结果。
  • 如果您在循环中使用它,请设置一个唯一的元素 id (el.id=),以便 get_error 函数可以引用正确的项目。
  • 设置 onerror (el.onerror=function) 行有点复杂,因为需要它调用 get_error 函数并传递 el.id - 如果只是设置了对该函数的正常引用(例如:el.onerror=get_error),那么就无法传递 el.id 参数。
  • 请记住,这仅检查文件是否存在。

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?

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.
  • 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.
  • 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.
  • remember that this only checks if a file does not exist.
最后的乘客 2024-10-26 07:33:58

你可以用这个

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

You can use this

function LinkCheck(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
辞取 2024-10-26 07:33:58

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

Javascript 不是这个任务

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 is not the task for this

送舟行 2024-10-26 07:33:58

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

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

美胚控场 2024-10-26 07:33:58

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

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

感情洁癖 2024-10-26 07:33:58

如果您使用 Nodejs,则不需要外部库,您所需要做的就是导入文件系统模块。请随意编辑以下代码:
const fs = require('fs')

const path = './file.txt'

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

  //file exists
})

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
})
白色秋天 2024-10-26 07:33:58

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文