File objects in javascript

File: File() constructor

The File() constructor creates a new File object instance.

Syntax

new File(bits, name) new File(bits, name, options) 

Parameters

An iterable object such as an Array , having ArrayBuffer s, TypedArray s, DataView s, Blob s, strings, or a mix of any of such elements, that will be put inside the File . Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings.

A string representing the file name or the path to the file.

An options object containing optional attributes for the file. Available options are as follows:

A string representing the MIME type of the content that will be put into the file. Defaults to a value of «» .

A number representing the number of milliseconds between the Unix time epoch and when the file was last modified. Defaults to a value of Date.now() .

Examples

const file = new File(["foo"], "foo.txt",  type: "text/plain", >); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

File and FileReader

A File object inherits from Blob and is extended with filesystem-related capabilities.

There are two ways to obtain it.

First, there’s a constructor, similar to Blob :

new File(fileParts, fileName, [options])
  • fileParts – is an array of Blob/BufferSource/String values.
  • fileName – file name string.
  • options – optional object:
    • lastModified – the timestamp (integer date) of last modification.

    Second, more often we get a file from or drag’n’drop or other browser interfaces. In that case, the file gets this information from OS.

    As File inherits from Blob , File objects have the same properties, plus:

    That’s how we can get a File object from :

       

    The input may select multiple files, so input.files is an array-like object with them. Here we have only one file, so we just take input.files[0] .

    FileReader

    FileReader is an object with the sole purpose of reading data from Blob (and hence File too) objects.

    It delivers the data using events, as reading from disk may take time.

    let reader = new FileReader(); // no arguments
    • readAsArrayBuffer(blob) – read the data in binary format ArrayBuffer .
    • readAsText(blob, [encoding]) – read the data as a text string with the given encoding ( utf-8 by default).
    • readAsDataURL(blob) – read the binary data and encode it as base64 data url.
    • abort() – cancel the operation.

    The choice of read* method depends on which format we prefer, how we’re going to use the data.

    • readAsArrayBuffer – for binary files, to do low-level binary operations. For high-level operations, like slicing, File inherits from Blob , so we can call them directly, without reading.
    • readAsText – for text files, when we’d like to get a string.
    • readAsDataURL – when we’d like to use this data in src for img or another tag. There’s an alternative to reading a file for that, as discussed in chapter Blob: URL.createObjectURL(file) .

    As the reading proceeds, there are events:

    • loadstart – loading started.
    • progress – occurs during reading.
    • load – no errors, reading complete.
    • abort – abort() called.
    • error – error has occurred.
    • loadend – reading finished with either success or failure.

    When the reading is finished, we can access the result as:

    The most widely used events are for sure load and error .

    Here’s an example of reading a file:

       

    As mentioned in the chapter Blob, FileReader can read not just files, but any blobs.

    We can use it to convert a blob to another format:

    • readAsArrayBuffer(blob) – to ArrayBuffer ,
    • readAsText(blob, [encoding]) – to string (an alternative to TextDecoder ),
    • readAsDataURL(blob) – to base64 data url.

    For Web Workers, there also exists a synchronous variant of FileReader , called FileReaderSync.

    Its reading methods read* do not generate events, but rather return a result, as regular functions do.

    That’s only inside a Web Worker though, because delays in synchronous calls, that are possible while reading from files, in Web Workers are less important. They do not affect the page.

    Summary

    File objects inherit from Blob .

    In addition to Blob methods and properties, File objects also have name and lastModified properties, plus the internal ability to read from filesystem. We usually get File objects from user input, like or Drag’n’Drop events ( ondragend ).

    FileReader objects can read from a file or a blob, in one of three formats:

    • String ( readAsText ).
    • ArrayBuffer ( readAsArrayBuffer ).
    • Data url, base-64 encoded ( readAsDataURL ).

    In many cases though, we don’t have to read the file contents. Just as we did with blobs, we can create a short url with URL.createObjectURL(file) and assign it to or . This way the file can be downloaded or shown up as an image, as a part of canvas etc.

    And if we’re going to send a File over a network, that’s also easy: network API like XMLHttpRequest or fetch natively accepts File objects.

    Источник

    File

    The File interface provides information about files and allows JavaScript in a web page to access their content.

    File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the element, or from a drag and drop operation’s DataTransfer object.

    A File object is a specific kind of Blob , and can be used in any context that a Blob can. In particular, FileReader , URL.createObjectURL() , createImageBitmap() , and XMLHttpRequest.send() accept both Blob s and File s.

    See Using files from web applications for more information and examples.

    Constructor

    Instance properties

    File.prototype.lastModified Read only Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight). File.prototype.lastModifiedDate Deprecated Read only Non-standard Returns the last modified Date of the file referenced by the File object. File.prototype.name Read only Returns the name of the file referenced by the File object. File.prototype.webkitRelativePath Read only Returns the path the URL of the File is relative to. File implements Blob , so it also has the following properties available to it: File.prototype.size Read only Returns the size of the file in bytes. File.prototype.type Read only Returns the MIME type of the file.

    Instance methods

    The File interface doesn’t define any methods, but inherits methods from the Blob interface: Blob.prototype.slice([start[, end[, contentType]]]) Returns a new Blob object containing the data in the specified range of bytes of the source Blob . Blob.prototype.stream() Transforms the File into a ReadableStream that can be used to read the File contents. Blob.prototype.text() Transforms the File into a stream and reads it to completion. It returns a promise that resolves with a string (text). Blob.prototype.arrayBuffer() Transforms the File into a stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer .

    Specifications

    Browser compatibility

    See also

    Found a content problem with this page?

    Источник

    File и FileReader

    Объект File наследуется от объекта Blob и обладает возможностями по взаимодействию с файловой системой.

    Есть два способа его получить.

    Во-первых, есть конструктор, похожий на Blob :

    new File(fileParts, fileName, [options])
    • fileParts – массив значений Blob / BufferSource /строки.
    • fileName – имя файла, строка.
    • options – необязательный объект со свойством:
      • lastModified – дата последнего изменения в формате таймстамп (целое число).

      Во-вторых, чаще всего мы получаем файл из или через перетаскивание с помощью мыши, или из других интерфейсов браузера. В этом случае файл получает эту информацию из ОС.

      Так как File наследует от Blob , у объектов File есть те же свойства плюс:

      В этом примере мы получаем объект File из :

         

      Через можно выбрать несколько файлов, поэтому input.files – псевдомассив выбранных файлов. Здесь у нас только один файл, поэтому мы просто берём input.files[0] .

      FileReader

      FileReader объект, цель которого читать данные из Blob (и, следовательно, из File тоже).

      Данные передаются при помощи событий, так как чтение с диска может занять время.

      let reader = new FileReader(); // без аргументов
      • readAsArrayBuffer(blob) – считать данные как ArrayBuffer
      • readAsText(blob, [encoding]) – считать данные как строку (кодировка по умолчанию: utf-8 )
      • readAsDataURL(blob) – считать данные как base64-кодированный URL.
      • abort() – отменить операцию.

      Выбор метода для чтения зависит от того, какой формат мы предпочитаем, как мы хотим далее использовать данные.

      • readAsArrayBuffer – для бинарных файлов, для низкоуровневой побайтовой работы с бинарными данными. Для высокоуровневых операций у File есть свои методы, унаследованные от Blob , например, slice , мы можем вызвать их напрямую.
      • readAsText – для текстовых файлов, когда мы хотим получить строку.
      • readAsDataURL – когда мы хотим использовать данные в src для img или другого тега. Есть альтернатива – можно не читать файл, а вызвать URL.createObjectURL(file) , детали в главе Blob.

      В процессе чтения происходят следующие события:

      • loadstart – чтение начато.
      • progress – срабатывает во время чтения данных.
      • load – нет ошибок, чтение окончено.
      • abort – вызван abort() .
      • error – произошла ошибка.
      • loadend – чтение завершено (успешно или нет).

      Когда чтение закончено, мы сможем получить доступ к его результату следующим образом:

      Наиболее часто используемые события – это, конечно же, load и error .

         

      Как упоминалось в главе Blob, FileReader работает для любых объектов Blob, а не только для файлов.

      Поэтому мы можем использовать его для преобразования Blob в другой формат:

      • readAsArrayBuffer(blob) – в ArrayBuffer ,
      • readAsText(blob, [encoding]) – в строку (альтернатива TextDecoder ),
      • readAsDataURL(blob) – в формат base64-кодированного URL.

      Для веб-воркеров доступен синхронный вариант FileReader , именуемый FileReaderSync.

      Его методы считывания read* не генерируют события, а возвращают результат, как это делают обычные функции.

      Но это только внутри веб-воркера, поскольку задержки в синхронных вызовах, которые возможны при чтении из файла, в веб-воркерах менее важны. Они не влияют на страницу.

      Итого

      File объекты наследуют от Blob .

      Помимо методов и свойств Blob , объекты File также имеют свойства name и lastModified плюс внутреннюю возможность чтения из файловой системы. Обычно мы получаем объекты File из пользовательского ввода, например, через или перетаскиванием с помощью мыши, в событии dragend .

      Объекты FileReader могут читать из файла или Blob в одном из трёх форматов:

      • Строка ( readAsText ).
      • ArrayBuffer ( readAsArrayBuffer ).
      • URL в формате base64 ( readAsDataURL ).

      Однако, во многих случаях нам не нужно читать содержимое файла. Как и в случае с Blob, мы можем создать короткий URL с помощью URL.createObjectURL(file) и использовать его в теге или . Таким образом, файл может быть загружен или показан в виде изображения, как часть canvas и т.д.

      А если мы собираемся отправить File по сети, то это также легко, поскольку в сетевые методы, такие как XMLHttpRequest или fetch , встроена возможность отсылки File .

      Источник

      Читайте также:  Php openssl private encrypt
Оцените статью