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

发布于 2024-08-22 17:08:02 字数 197 浏览 6 评论 0原文

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

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

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.

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

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

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

发布评论

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

评论(10

忆沫 2024-08-29 17:08:02

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

此示例不是异步的,但如果您愿意,您可以这样做。

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

If it's on the same server as your calling function you can use 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'));
这样的小城市 2024-08-29 17:08:02

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

document.lastModified 

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

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.

疾风者 2024-08-29 17:08:02

使用现代的 fetch 方法:

var lastMod = null;
fetch(xmlPath).then(r => {
    lastMod = r.headers.get('Last-Modified');
    return r.text();
})

Using the modern fetch method:

var lastMod = null;
fetch(xmlPath).then(r => {
    lastMod = r.headers.get('Last-Modified');
    return r.text();
})
‘画卷フ 2024-08-29 17:08:02

FutureBoy 的答案 格式化为完整函数并添加 HEAD 方法和日期转换,代码将如下所示。

function fetchLastModified(url, callback) {
    fetch(url, {method: "HEAD"})
        .then(r => {callback(new Date(r.headers.get('Last-Modified')))});
}

HEAD 减少了传输的数据量,仅包含 HTTP 标头。由于 FutureBoy 的答案仅使用了标头,因此我编写了仅提取标头的函数。请参阅 Mozilla.org 的 HEAD 文档

Formatting FutureBoy's answer as a full function and adding a HEAD method and date conversion, the code would appear as follows.

function fetchLastModified(url, callback) {
    fetch(url, {method: "HEAD"})
        .then(r => {callback(new Date(r.headers.get('Last-Modified')))});
}

HEAD reduces the amount of data transmitted to just include the HTTP headers. Since FutureBoy's answer just used the headers, I wrote the function to only pull the headers. See Mozilla.org's HEAD documentation.

-黛色若梦 2024-08-29 17:08:02

File.lastModified

您可以使用 File.lastModified< /code>属性获取文件的最后修改日期,以自 Unix 纪元以来的毫秒数表示。

示例:

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

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

File.lastModified

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

Example:

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

console.log(`Last Modified Date: ${lastModifiedDate}`);
别挽留 2024-08-29 17:08:02

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

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

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

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

幻梦 2024-08-29 17:08:02

我在 JS 方面相对较新,所以我很难按照上面的答案来产生一些可行的东西。我最终确实根据上面 Kennebec 的答案创建了一些东西,但立即收到了来自 Chrome 的可怕警告,同步调用 XMLHttpRequest() 现已被弃用,并且很快会导致脚本崩溃错误。

因此,这里有一个即插即用的脚本,它将为您提供服务器上文件的修改时间,非常异步且合规:

let file = "../yourfile.html";

function makeRequest(url) {
    return new Promise(function (resolve, reject) {
        let xhr = new XMLHttpRequest();
        let rand = Math.floor(Math.random() * (99999 - 11111) + 11111);
        let newurl = url+"?v="+rand;
        xhr.open("HEAD", newurl);
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                resolve(xhr.getResponseHeader("Last-Modified"));
            } else {
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            }
        };
        xhr.onerror = function () {
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        };
        xhr.send();
    });
}

document.onload = rando();

async function rando(){
    let result = await makeRequest(file);
    let time = Date.parse(result)/1000;
    console.log(time);
}

希望这有助于节省一些时间。

顺便说一句,我需要这个脚本的原因是向动态加载的 CSS 样式表附加一个变量。通过使用修改时间作为变量,它可以防止浏览器缓存该死的样式表(如果它们自上次加载以来已被修改)。这也是一个众所周知的缓存破坏 HTML 文件的技巧,但在 PHP 中更容易做到!

I'm relatively new at JS, so I've had a hard time following the above answers to produce something workable. I finally did create something based off of Kennebec's answer above, but promptly received a dire warning from Chrome that calling XMLHttpRequest() synchronously is now deprecated, and will soon result in a script-crashing error.

So here's a plug-and-play script that will give you the modification time of a file on your server, gloriously asynchronous and compliant:

let file = "../yourfile.html";

function makeRequest(url) {
    return new Promise(function (resolve, reject) {
        let xhr = new XMLHttpRequest();
        let rand = Math.floor(Math.random() * (99999 - 11111) + 11111);
        let newurl = url+"?v="+rand;
        xhr.open("HEAD", newurl);
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                resolve(xhr.getResponseHeader("Last-Modified"));
            } else {
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            }
        };
        xhr.onerror = function () {
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        };
        xhr.send();
    });
}

document.onload = rando();

async function rando(){
    let result = await makeRequest(file);
    let time = Date.parse(result)/1000;
    console.log(time);
}

Hope this helps save some time.

Incidentally, the reason I needed this script was to append a variable to dynamically-loaded CSS stylesheets. By using the modification time as the variable, it prevents the browser from caching the damn stylesheets if they've been modified since the last load. This is also a well-known trick for cache busting HTML files, but it's a lot easier to do in PHP!

半衬遮猫 2024-08-29 17:08:02

要获取一组文件的最后修改日期,请迭代各个时间戳并重新调整最新的时间戳。显然,当仅传递单个项目时,也适用于单个文件。

const ns = {
  files: ['/index.html', '/sw.js', '/style.css'], //sample set of typical client files
  last_mod: async(f = []) => {
    let ts = 0;
    for (let i of f) {
      let d = await fetch(i) //get each file
        .then(r => r.headers.get('Last-Modified')) //get last modified date in raw text format
        .catch(e => console.error(e));
      ts = Math.max(ts, +new Date(d)); //latest timestamp
    }
    return ts;
  }
}

console.log('Client last modified:', new Date(await ns.last_mod(ns.files)));

To get the last modified date for a set of files, iterate through the individual timestamps and retun the latest. Obviously also works for a single file when passing in just a single item.

const ns = {
  files: ['/index.html', '/sw.js', '/style.css'], //sample set of typical client files
  last_mod: async(f = []) => {
    let ts = 0;
    for (let i of f) {
      let d = await fetch(i) //get each file
        .then(r => r.headers.get('Last-Modified')) //get last modified date in raw text format
        .catch(e => console.error(e));
      ts = Math.max(ts, +new Date(d)); //latest timestamp
    }
    return ts;
  }
}

console.log('Client last modified:', new Date(await ns.last_mod(ns.files)));

鲜血染红嫁衣 2024-08-29 17:08:02

我喜欢 @CrazyIvan1974 使用 HEAD 的答案,但我更喜欢等待语法,所以这里是一个等待版本 -

async function fetchLastModified(url) {
      const response = await fetch(url, { method: "HEAD" });
      const lastModified = new Date(response.headers.get('Last-Modified'));
      return lastModified;
}

const url = 'https://url_of_file_to_check/thefile.html';
const lastModified = await fetchLastModified(url);

I liked @CrazyIvan1974's answer with use of HEAD, but I prefer the await syntax, so here is an await version -

async function fetchLastModified(url) {
      const response = await fetch(url, { method: "HEAD" });
      const lastModified = new Date(response.headers.get('Last-Modified'));
      return lastModified;
}

const url = 'https://url_of_file_to_check/thefile.html';
const lastModified = await fetchLastModified(url);
定格我的天空 2024-08-29 17:08:02

不,不是。您无法通过 JavaScript 访问文件系统

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

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