檔案:lastModified 屬性
注意:此功能在 Web Workers 中可用。
File 介面的只讀屬性 lastModified 提供檔案的最後修改日期,表示自 Unix 紀元(1970 年 1 月 1 日午夜)以來的毫秒數。沒有已知最後修改日期的檔案將返回當前日期。
值
一個數字,表示自 Unix 紀元以來的毫秒數。
示例
下面的示例將遍歷您選擇的檔案,並打印出每個檔案是否在過去一年內被修改過。
HTML
html
<input type="file" id="file-picker" name="fileList" multiple />
<output id="output"></output>
JavaScript
js
const output = document.getElementById("output");
const filePicker = document.getElementById("file-picker");
filePicker.addEventListener("change", (event) => {
const files = event.target.files;
const now = new Date();
output.textContent = "";
for (const file of files) {
const date = new Date(file.lastModified);
// true if the file hasn't been modified for more than 1 year
const stale = now.getTime() - file.lastModified > 31_536_000_000;
output.textContent += `${file.name} is ${
stale ? "stale" : "fresh"
} (${date}).\n`;
}
});
結果
動態建立的檔案
如果檔案是動態建立的,可以在 File() 建構函式中提供最後修改時間。如果缺失,lastModified 將繼承 File 物件建立時 Date.now() 的當前時間。
js
const fileWithDate = new File([], "file.bin", {
lastModified: new Date(2017, 1, 1),
});
console.log(fileWithDate.lastModified); // returns 1485903600000
const fileWithoutDate = new File([], "file.bin");
console.log(fileWithoutDate.lastModified); // returns current time
時間精度降低
為了提供針對時間攻擊和指紋識別的保護,someFile.lastModified 的精度可能會根據瀏覽器設定進行舍入。在 Firefox 中,privacy.reduceTimerPrecision 首選項預設啟用,預設為 2ms。您還可以啟用 privacy.resistFingerprinting,在這種情況下,精度將是 100ms 或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds 的值(以較大者為準)。
例如,在時間精度降低的情況下,someFile.lastModified 的結果將始終是 2 的倍數,或者在啟用 privacy.resistFingerprinting 時是 100(或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds)的倍數。
js
// reduced time precision (2ms) in Firefox 60
someFile.lastModified;
// Might be:
// 1519211809934
// 1519211810362
// 1519211811670
// …
// reduced time precision with `privacy.resistFingerprinting` enabled
someFile.lastModified;
// Might be:
// 1519129853500
// 1519129858900
// 1519129864400
// …
規範
| 規範 |
|---|
| File API # dfn-lastModified |
瀏覽器相容性
載入中…