You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A[File](https://www.w3.org/TR/FileAPI/#dfn-file)object inherits from`Blob`, but is extended with filesystem-related capabilities.
3
+
Объект[File](https://www.w3.org/TR/FileAPI/#dfn-file)наследуется от объекта`Blob`, но дополняется возможностями подобных файловых систем.
4
4
5
-
There are two ways to obtain it.
5
+
Есть два способа его получить.
6
6
7
-
First, there's a constructor, similar to`Blob`:
7
+
Во-первых, есть конструктор, похожий на`Blob`:
8
8
9
9
```js
10
10
newFile(fileParts, fileName, [options])
11
11
```
12
12
13
-
-**`fileParts`** -- is an array of Blob/BufferSource/String value, same as`Blob`.
14
-
-**`fileName`** -- file name string.
15
-
-**`options`** -- optional object:
16
-
-**`lastModified`** -- a timestamp (integer date) of last modification.
13
+
-**`fileParts`** -- массив значений Blob/BufferSource/String, такой же как`Blob`.
14
+
-**`fileName`** -- строка имени файла.
15
+
-**`options`** -- необязательный объект:
16
+
-**`lastModified`** -- timestamp (целочисленная дата) последнего изменения.
17
17
18
-
Second, more often we get a file from `<input type="file">` or drag'n'drop or other browser interfaces. Then the file gets these from OS.
18
+
Во-вторых, чаще всего мы получаем файл из `<input type="file">`, или drag'n'drop, или других интерфейсов браузера. Затем этот файл получает нужную информацию из ОС.
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]`.
36
+
Через `<input>` можно выбрать несколько файлов, поэтому `input.files` -- массивоподобный объект выбранных файлов. Здесь у нас только один файл, поэтому мы просто берем `input.files[0]`.
37
37
```
38
38
39
39
## FileReader
40
40
41
-
[FileReader](https://www.w3.org/TR/FileAPI/#dfn-filereader)is an object with the sole purpose of reading from `Blob`(and hence`File`too) objects.
41
+
Единственная цель объекта [FileReader](https://www.w3.org/TR/FileAPI/#dfn-filereader)заключается в считывании информации из объекта `Blob`и, следовательно,`File`тоже.
42
42
43
-
It's event based, as reading from disk may take time.
43
+
В основе лежат события, так как чтение с диска может занять некоторое время.
44
44
45
-
The constructor:
45
+
Конструктор:
46
46
47
47
```js
48
-
let reader =newFileReader(); //no arguments
48
+
let reader =newFileReader(); //без аргументов
49
49
```
50
+
51
+
Основные методы:
50
52
51
-
The main methods:
53
+
-**`readAsArrayBuffer(blob)`** -- считать данные как `ArrayBuffer`
54
+
-**`readAsText(blob, [encoding])`** -- считать данные как строку (кодировка по умолчанию: `utf-8`)
55
+
-**`readAsDataURL(blob)`** -- считать данные как base64 (data: URL).
56
+
-**`abort()`** -- отменить операцию.
52
57
53
-
-**`readAsArrayBuffer(blob)`** -- read the data as `ArrayBuffer`
54
-
-**`readAsText(blob, [encoding])`** -- read the data as a string (encoding is `utf-8` by default)
55
-
-**`readAsDataURL(blob)`** -- encode the data as base64 data url.
56
-
-**`abort()`** -- cancel the operation.
58
+
В процессе загрузки можно "слушать" следующие события:
59
+
-`loadstart` -- загрузка начата.
60
+
-`progress` -- срабатывает в то время, когда происходит считывание.
61
+
-`load` -- нет ошибок, загрузка окончена.
62
+
-`abort` -- вызван `abort()`.
63
+
-`error` -- произошла ошибка.
64
+
-`loadend` -- загрузка закончилась успешно или неудачей.
57
65
58
-
As the reading proceeds, there are events:
59
-
-`loadstart` -- loading started.
60
-
-`progress` -- occurs during reading.
61
-
-`load` -- no errors, reading complete.
62
-
-`abort` -- `abort()` called.
63
-
-`error` -- error has occured.
64
-
-`loadend` -- reading finished with either success or failure.
66
+
Когда загрузка закончится, мы сможем получить доступ к её результату следующим образом:
67
+
-`reader.result` результат считывания (если оно успешно)
68
+
-`reader.error` объект ошибки (при неудаче).
65
69
66
-
When the reading is finished, we can access the result as:
67
-
-`reader.result` is the result (if successful)
68
-
-`reader.error` is the error (if failed).
70
+
Наиболее часто используемые события это, конечно же, `load` и `error`.
69
71
70
-
The most widely used events are for sure `load` and `error`.
71
-
72
-
Here's an example of reading a file:
72
+
Вот пример загрузки файла:
73
73
74
74
```html run
75
75
<inputtype="file"onchange="readFile(this)">
@@ -94,35 +94,34 @@ function readFile(input) {
94
94
</script>
95
95
```
96
96
97
-
```smart header="`FileReader`for blobs"
98
-
As mentioned in the chapter <info:blob>, `FileReader`works for any blobs, not just files.
97
+
```smart header="`FileReader`для Blob"
98
+
Как упоминалось в главе <info:blob>, `FileReader`работает для любых объектов Blob, а не только для файлов.
99
99
100
-
So we can use it to convert a blob to another format:
101
-
-`readAsArrayBuffer(blob)` -- to`ArrayBuffer`,
102
-
-`readAsText(blob, [encoding])` -- to string (an alternative to`TextDecoder`),
103
-
-`readAsDataURL(blob)` -- to base64 data url.
100
+
Поэтому, мы можем использовать его для преобразования Blob в другой формат:
101
+
-`readAsArrayBuffer(blob)` -- в`ArrayBuffer`,
102
+
-`readAsText(blob, [encoding])` -- в строку (альтернатива`TextDecoder`),
103
+
-`readAsDataURL(blob)` -- в base64 (data: URL).
104
104
```
105
105
106
106
107
-
```smart header="`FileReaderSync` is available for workers only"
108
-
For Web Workers, there also exists a synchronous variant of `FileReader`, called [FileReaderSync](https://www.w3.org/TR/FileAPI/#FileReaderSync).
107
+
```smart header="`FileReaderSync` доступен только для Web Worker'ов"
108
+
Для Web Worker'ов существует также и синхронный вариант `FileReader`, именуемый [FileReaderSync](https://www.w3.org/TR/FileAPI/#FileReaderSync).
109
109
110
-
Its reading methods `read*` do not generate events, but rather return a result, as regular functions do.
110
+
Его методы считывания `read*` не генерируют события, а скорее возвращают результат, как это делают обычные функции.
111
111
112
-
That's only inside a Web Worker though, because delays and hang-ups in Web Workers are less important, they do not affect the page.
112
+
Но это только внутри Web Worker'а, поскольку задержки и зависания в Web Worker'ах менее важны, они не влияют на страницу.
113
113
```
114
114
115
-
## Summary
115
+
## Итого
116
116
117
-
`File`objects inherit from`Blob`.
117
+
`File`объекты наследуемые от`Blob`.
118
118
119
-
In addition to `Blob` methods and properties, `File`objects also have`fileName`and`lastModified` properties, plus the internal ability to read from filesystem. We usually get`File`objects from user input, like `<input>`or drag'n'drop.
119
+
Помимо методов и свойств `Blob`, объекты `File`также имеют свойства`fileName`и`lastModified`, плюс внутреннюю возможность чтения из файловой системы. Обычно мы получаем`File`объекты из пользовательского ввода, такого как `<input>`или drag'n'drop.
120
120
121
-
`FileReader`objects can read from a file or a blob, in one of three formats:
122
-
-String (`readAsText`).
121
+
Объекты `FileReader`могут читаться из файла или Blob, в одном из трех форматов:
122
+
-Строка (`readAsText`).
123
123
-`ArrayBuffer` (`readAsArrayBuffer`).
124
-
- Data url, base-64 encoded (`readAsDataURL`).
125
-
126
-
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 `<a>` or `<img>`. This way the file can be downloaded or shown up as an image, as a part of canvas etc.
124
+
- Data: url, c кодировкой base-64 (`readAsDataURL`).
127
125
128
-
And if we're going to send a `File` over a network, that's also easy, as network API like `XMLHttpRequest` or `fetch` natively accepts `File` objects.
126
+
Однако во многих случаях нам не нужно читать содержимое файла. Как и в случае с Blob, мы можем создать короткий url с помощью `URL.createObjectURL(file)` и назначить его для `<a>` или `<img>`. Таким образом, файл может быть загружен или показан в виде изображения, как часть canvas и т.д.
127
+
И если мы собираемся отправить `File` по сети, это также легко, поскольку сетевой API, такой как `XMLHttpRequest` или `fetch`, изначально принимает объекты `File`.
0 commit comments