File

File 介面提供了檔案的資訊並且允許網頁中的 JavaScript 存取檔案的內容。

File 物件通常是從使用者於 <input> (en-US) 元素選擇之檔案所回傳的 FileList 物件當中取得,也可以來自拖放操作所產生的 DataTransfer (en-US) 物件之中,或是由 HTMLCanvasElement (en-US) 物件(元素物件)執行 mozGetAsFile() 方法後回傳。在 Gecko 引擎中,有專屬的程式碼能不需使用者操作即建立 File 物件來表示本地端的任一檔案(請參考 Implementation notes 以閱讀更多資訊)。

File 物件是一種特殊的 Blob,且可被用在任何接受 Blob 物件的地方。特別是 FileReaderURL.createObjectURL() (en-US)createImageBitmap() (en-US)XMLHttpRequest.send() 都能夠同樣接受 Blob 以及 File

請參考在網頁應用程式中使用本地檔案的更多細節與範例。

Blob File

建構式

File()

回傳一個新建構的 File 物件。

屬性

File.lastModified (en-US) Read only

回值檔案的最後修改時間,為 UNIX epoch 毫秒(自西元 1970 年一月 1 日零時至今)。

File.lastModifiedDate (en-US) Read only 已棄用

File 物件所代表之檔案的最後修改日期(Date)。

File.name Read only

File 物件所代表之檔案的名稱。

File.size (en-US) Read only

回傳檔案大小。

File.webkitRelativePath (en-US) Read only 非標準

回傳相對於 File 的網址位置。

File.type (en-US) Read only

回傳檔案的 MIME 類型。

File 實作了 Blob,因此它也有以下可用屬性:

File.size (en-US) Read only

回傳檔案大小(單位為位元組)。

File.type (en-US) Read only

回傳檔案的 MIME (en-US) 類型。

方法

File 介面沒有定義任何方法,但繼承了 Blob 介面的方法:

Blob.slice([start[, end[, contentType]]]) (en-US)

回傳新的 Blob 物件,包含 Blob 來源之指定位元組範圍的資料。

規範

Specification
File API
# file-section

瀏覽器相容性

BCD tables only load in the browser

實作備註

  • In Gecko, you can use this API from within chrome code. See Using the DOM File API in chrome code for details. To use it from chrome code, JSM and Bootstrap scope, you have to import it using Cu.importGlobalProperties(['File']);
  • Starting from Gecko 6.0, privileged code (such as extensions) can pass an nsIFile object to the DOM File constructor to specify the file to reference.
  • Starting from Gecko 8.0, you can use new File to create File objects from XPCOM component code instead of having to instantiate the nsIDOMFile object directly. The constructor takes, in contrast to Blob, as second argument the filename. The filename can be any String.
    new File(
      Array parts,
      String filename,
      BlobPropertyBag properties
    );
    
  • The following non-standard properties and methods were removed in Gecko 7: File.fileName, File.fileSize (en-US), File.getAsBinary(), File.getAsDataURL(), File.getAsText(string encoding) (Firefox bug 661876). Standard properties File.name, Blob.size, and methods on FileReader should be used instead.

參見