简体   繁体   English

在不使用 XMLHttpRequest 的情况下检查服务器上是否存在文件

[英]Checking if file exists on server without using XMLHttpRequest

Is there a quicker solution to checking if a file exists on a server?是否有更快的解决方案来检查服务器上是否存在文件? I am currently using this approach which seems pretty common on here but it is extremely slow.我目前正在使用这种方法,这在这里似乎很常见,但速度非常慢。

            async checkFileExist(path, timeout = 200000)
        {
            let totalTime = 0;
            let checkTime = timeout / 10;
            var self = this;

            return await new Promise((resolve, reject) => {
                const timer = setInterval(function () {

                    totalTime += checkTime;

                    let fileExists = self.fileExist(path);

                    if (fileExists || totalTime >= timeout) {
                        clearInterval(timer);

                        resolve(fileExists);

                    }
                }, checkTime);
            })
        },
        fileExist(urlToFile) {
            var xhr = new XMLHttpRequest();
            xhr.open('HEAD', urlToFile, false);
            xhr.send();

            if(xhr.status == "404") {
                return false;
            } else {
                return true;
            }
        },

Mount function for component.为组件安装 function。

        mounted() {
        alert('1st test')
        var self = this
        this.checkFileExist(this.filedir).then(function (response) {
            console.log("Success!", response);
            self.loadingFile = false;
            self.renderPage(this.pageNum);
            alert('2nd test')
        }, function (error) {
            console.error("Failed!", error);
        })
    },

That won't tell you if a file exists.这不会告诉你文件是否存在。 It will tell you if a URL finds a resource.它会告诉您 URL 是否找到资源。 It's an important distinction since a URL could be handled by server-side code and not a simple static file, while a file might exist and not have a URL.这是一个重要的区别,因为 URL 可以由服务器端代码处理,而不是简单的 static 文件,而文件可能存在但没有 ZE6B391A8D2C4D45903A23A8B65857。

Making an HTTP request is the simplest way to find out if a URL finds a resource.发出 HTTP 请求是确定 URL 是否找到资源的最简单方法。 There are other ways to make HTTP requests (such as the fetch API), but they aren't faster, just different.还有其他方法可以发出 HTTP 请求(例如 fetch API),但它们并不快,只是不同而已。

A potentially faster (but much more complicated) way would be to use a Websocket.一种可能更快(但更复杂)的方法是使用 Websocket。 You need to have it open before you wanted to know if the URL exists (otherwise any time savings are lost to establishing the Websocket connection) and you'd need to write the server side code which reacted to the Websocket message by working out if the desired URL existed and telling the client.在您想知道 URL 是否存在之前,您需要先打开它(否则建立 Websocket 连接会浪费任何时间)并且您需要编写对 ZFEA54C8A1121D68BZBE6BFA 做出反应的服务器端代码所需的 URL 存在并告诉客户。

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

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