问题描述
我想检查本地是否存在文件,即 HTML 文件所在的位置.它必须是 JavaScript.JavaScript 永远不会被禁用.jQuery 不好但可以做.
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.
顺便说一下,我正在为 Mac 制作一个钛应用程序,所以我正在寻找一种方法来保护我的文件免受点击显示包内容"的人的影响.
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".
推荐答案
您的问题模棱两可,因此根据您真正想要实现的目标,有多种可能的答案.
Your question is ambiguous, so there are multiple possible answers depending on what you're really trying to achieve.
如果您正在开发我猜想使用 Titanium 的桌面应用程序,那么您可以使用 FileSystem 模块的 getFile 来获取文件对象,然后使用exists 方法检查它是否存在.
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.
以下是取自 Appcelerator 网站的示例:
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.');
...
}
对于那些认为他是在询问常见的 Web 开发情况的人,那么我会给出以下两个答案:
1) 您想检查服务器端文件是否存在.在这种情况下,您可以使用 ajax 请求尝试获取文件并对收到的答案做出反应.不过,请注意,您只能检查 Web 服务器公开的文件.更好的方法是编写一个服务器端脚本(例如,php)来为您进行检查,给定文件名并通过 ajax 调用该脚本.另外,请注意,如果您不够小心,很容易在应用程序/服务器中创建安全漏洞.
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) 您想检查客户端文件是否存在.在这种情况下,正如其他人向您指出的那样,出于安全原因,这是不允许的(尽管 IE 过去通过 ActiveX 和 Scripting.FileSystemObject 类允许这样做)并且这样就好了(没有人希望您能够通过他们的文件),所以忘记这个.
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.
这篇关于仅使用 JavaScript 检查本地文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!