Skip to content

Commit 2651b4a

Browse files
Merge pull request #215 from shchegol/master
File and FileReader
2 parents 4a10285 + 5361378 commit 2651b4a

1 file changed

Lines changed: 53 additions & 54 deletions

File tree

4-binary/04-file/article.md

Lines changed: 53 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1-
# File and FileReader
1+
# File и FileReader
22

3-
A [File](https://www.w3.org/TR/FileAPI/#dfn-file) object inherits from `Blob` and is extended with filesystem-related capabilities.
3+
Объект [File](https://www.w3.org/TR/FileAPI/#dfn-file) наследуется от объекта `Blob` и возможностями по взаимодействию с файловой системой.
44

5-
There are two ways to obtain it.
5+
Есть два способа его получить.
66

7-
First, there's a constructor, similar to `Blob`:
7+
Во-первых, есть конструктор, похожий на `Blob`:
88

99
```js
1010
new File(fileParts, fileName, [options])
1111
```
1212

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 (целое число).
1717

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">` или через перетаскивание с помощью мыши, или других интерфейсов браузера. Затем этот файл получает нужную информацию из ОС.
1919

20-
For instance:
20+
Например:
2121

2222
```html run
2323
<input type="file" onchange="showFile(this)">
@@ -26,50 +26,50 @@ For instance:
2626
function showFile(input) {
2727
let file = input.files[0];
2828
29-
alert(`File name: ${file.name}`); // e.g my.png
30-
alert(`Last modified: ${file.lastModified}`); // e.g 1552830408824
29+
alert(`File name: ${file.name}`); // например, my.png
30+
alert(`Last modified: ${file.lastModified}`); // например, 1552830408824
3131
}
3232
</script>
3333
```
3434

3535
```smart
36-
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]`.
3737
```
3838

3939
## FileReader
4040

41-
[FileReader](https://www.w3.org/TR/FileAPI/#dfn-filereader) is an object with the sole purpose of reading data from `Blob` (and hence `File` too) objects.
41+
[FileReader](https://www.w3.org/TR/FileAPI/#dfn-filereader) объект, цель которого: читать данные из `Blob` (и, следовательно, `File` тоже).
4242

43-
It delivers the data using events, as reading from disk may take time.
43+
Данные передаются при помощи событий, так как чтение с диска может занять время.
4444

45-
The constructor:
45+
Конструктор:
4646

4747
```js
48-
let reader = new FileReader(); // no arguments
48+
let reader = new FileReader(); // без аргументов
4949
```
50+
51+
Основные методы:
5052

51-
The main methods:
53+
- **`readAsArrayBuffer(blob)`** -- считать данные как `ArrayBuffer`
54+
- **`readAsText(blob, [encoding])`** -- считать данные как строку (кодировка по умолчанию: `utf-8`)
55+
- **`readAsDataURL(blob)`** -- считать данные как base64-кодированный URL.
56+
- **`abort()`** -- отменить операцию.
5257

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` -- чтение завершено (успешно или нет).
5765

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 occurred.
64-
- `loadend` -- reading finished with either success or failure.
66+
Когда чтение закончено, мы сможем получить доступ к его результату следующим образом:
67+
- `reader.result` результат чтения (если оно успешно)
68+
- `reader.error` объект ошибки (при неудаче).
6569

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`.
6971

70-
The most widely used events are for sure `load` and `error`.
71-
72-
Here's an example of reading a file:
72+
Вот пример чтения файла:
7373

7474
```html run
7575
<input type="file" onchange="readFile(this)">
@@ -94,35 +94,34 @@ function readFile(input) {
9494
</script>
9595
```
9696

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, а не только для файлов.
9999

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-кодированного URL.
104104
```
105105
106106
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` доступен только для веб-воркеров"
108+
Для веб-воркеров существует также и синхронный вариант `FileReader`, именуемый [FileReaderSync](https://www.w3.org/TR/FileAPI/#FileReaderSync).
109109
110-
Its reading methods `read*` do not generate events, but rather return a result, as regular functions do.
110+
Его методы считывания `read*` не генерируют события, а возвращают результат, как это делают обычные функции.
111111
112-
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.
112+
Но это только внутри веб-воркера, поскольку задержки в синхронных вызовах, которые возможны при чтении из файла, в веб-воркерах менее важны. Они не влияют на страницу.
113113
```
114114

115-
## Summary
115+
## Итого
116116

117-
`File` objects inherit from `Blob`.
117+
`File` объекты наследуют от `Blob`.
118118

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>` или перетаскиванием с помощью мыши.
120120

121-
`FileReader` objects can read from a file or a blob, in one of three formats:
122-
- String (`readAsText`).
121+
Объекты `FileReader` могут читать из файла или Blob в одном из трёх форматов:
122+
- Строка (`readAsText`).
123123
- `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+
- URL в формате base64 (`readAsDataURL`).
127125

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

Comments
 (0)