是否可以使用 Javascript 检索文件的最后修改日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2313620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:44:17  来源:igfitidea点击:

Is it possible to retrieve the last modified date of a file using Javascript?

javascriptmetadata

提问by Riddari

I have a set of links on a web page that link to PDF forms and .doc forms. These files are not stored in a database, simply stored as they are, locally on the server. Is it possible to retrieve the last modified date of a PDF or DOC file using Javascript? I don't have any specific need to use Javascript, but it is preferable.

我在网页上有一组链接到 PDF 表单和 .doc 表单的链接。这些文件不存储在数据库中,只是按原样存储在服务器本地。是否可以使用 Javascript 检索 PDF 或 DOC 文件的最后修改日期?我对使用 Javascript 没有任何特定需求,但最好使用它。

UPDATE:Now that I realize that Javascript can't access the filesystem, is there an alternative method?

更新:现在我意识到 Javascript 无法访问文件系统,是否有替代方法?

回答by kennebec

If it's on the same server as your calling function you can use XMLHttpRequest-

如果它与您的调用函数在同一台服务器上,您可以使用 XMLHttpRequest-

This example is not asynchronous, but you can make it so if you wish.

这个例子不是异步的,但如果你愿意,你可以这样做。

function fetchHeader(url, wch) {
    try {
        var req=new XMLHttpRequest();
        req.open("HEAD", url, false);
        req.send(null);
        if(req.status== 200){
            return req.getResponseHeader(wch);
        }
        else return false;
    } catch(er) {
        return er.message;
    }
}

alert(fetchHeader(location.href,'Last-Modified'));

回答by j-p

This seems to be useful, and works for me - giving you the 'local' date

这似乎很有用,并且对我有用 - 为您提供“本地”日期

document.lastModified 

Compared to the above selection of req.getResponseHeader() it's one less round trip/http call.

与上面选择的 req.getResponseHeader() 相比,它少了一次往返/http 调用。

回答by Grant Miller

File.lastModified

文件.lastModified

You can use the File.lastModifiedproperty to obtain the last modified date of a file as the number of milliseconds since the Unix epoch.

您可以使用该File.lastModified属性获取文件的最后修改日期,作为自 Unix 纪元以来的毫秒数。

Example:

例子:

const file = document.getElementById('input').files[0];
const lastModifiedDate = new Date(file.lastModified);

console.log(`Last Modified Date: ${lastModifiedDate}`);

回答by jldupont

If an interface is exposed through HTTP, you can. Another way of saying: expose a WebService end-point to gain access to this information.

如果接口通过 HTTP 公开,则可以。另一种说法:公开 WebService 端点以访问此信息。

Of course, you can't have direct access to the filesystem for security reasons.

当然,出于安全原因,您不能直接访问文件系统。

回答by Naeem Sarfraz

No, it's not. You can't access the file system through JavaScript

不,这不对。无法通过 JavaScript 访问文件系统