Class: DownloadItem
Class: DownloadItem
Контроль загрузки файлов из удаленных источников.
Process: Main
This class is not exported from the 'electron'
module. Он доступен только в качестве возвращаемого значения других методов в Electron API.
DownloadItem
это EventEmitter, который представляет элемент загрузки в Electron. Он используется в событии will-download
класса Session
и позволяет пользователям управлять элементом загрузки.
// В основном процессе.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.session.on('will-download', (event, item, webContents) => {
// Установите путь сохранения, чтобы Electron не отображал диалоговое окно сохранения.
item.setSavePath('/tmp/save.pdf')
item.on('updated', (event, state) => {
if (state === 'interrupted') {
console.log('Download is interrupted but can be resumed')
} else if (state === 'progressing') {
if (item.isPaused()) {
console.log('Download is paused')
} else {
console.log(`Received bytes: ${item.getReceivedBytes()}`)
}
}
})
item.once('done', (event, state) => {
if (state === 'completed') {
console.log('Download successfully')
} else {
console.log(`Download failed: ${state}`)
}
})
})
События экземпляра
Событие: 'updated'
Возвращает:
- Событие типа
event
state
string - Can beprogressing
orinterrupted
.
Возникает, когда загрузка была обновлена и не завершена.
state
может быть одним из следующих:
progressing
- Загрузка находится в процессе загрузки.interrupted
- загрузка прервалась и может быть возобновлена.
Событие: 'done'
Возвращает:
- Событие типа
event
state
string - Can becompleted
,cancelled
orinterrupted
.
Emitted when the download is in a terminal state. This includes a completed download, a cancelled download (via downloadItem.cancel()
), and interrupted download that can't be resumed.
state
может быть одним из следующих:
completed
- Загрузка завершена успешно.cancelled
- загрузка была отменена.interrupted
- загрузка прервалась и не может быть возобновлена.
Методы экземпляра
Объект downloadItem
имеет следующие методы:
downloadItem.setSavePath(path)
path
string - Set the save file path of the download item.
API доступен только в сессии will-download
функции обратного вызова. If path
doesn't exist, Electron will try to make the directory recursively. Если пользователь не устанавливает путь сохранения через API, Electron будет использовать исходную процедуру для определения пути сохранения; здесь обычно вызывается диалоговое окно сохранения.
downloadItem.getSavePath()
Returns string
- The save path of the download item. This will be either the path set via downloadItem.setSavePath(path)
or the path selected from the shown save dialog.
downloadItem.setSaveDialogOptions(options)
This API allows the user to set custom options for the save dialog that opens for the download item by default. API доступен только в сессии will-download
функции обратного вызова.
downloadItem.getSaveDialogOptions()
Возвращает SaveDialogOptions
- Возвращает ранее установленный объект downloadItem.setSaveDialogOptions(options)
.
downloadItem.pause()
Приостановить скачивание.
downloadItem.isPaused()
Returns boolean
- Whether the download is paused.
downloadItem.resume()
Resumes the download that has been paused.
[!NOTE] To enable resumable downloads the server you are downloading from must support range requests and provide both
Last-Modified
andETag
header values. В противном случаеresume()
удалит ранее полученные байты и перезапустит загрузку с начала.
downloadItem.canResume()
Возвращает boolean
- Может ли загрузка возобновиться.
downloadItem.cancel()
Отменяет операцию загрузки.
downloadItem.getURL()
Возвращает string
- URL источника, из которого загружается элемент.
downloadItem.getMimeType()
Возвращает string
- Файлы mime типа.
downloadItem.hasUserGesture()
Возвращает boolean
- Есть ли у загрузки пользовательский жест.
downloadItem.getFilename()
Возвращает string
- Имя файла элемента загрузки.
[!NOTE] The file name is not always the same as the actual one saved in local disk. If user changes the file name in a prompted download saving dialog, the actual name of saved file will be different.
downloadItem.getCurrentBytesPerSecond()
Returns Integer
- The current download speed in bytes per second.
downloadItem.getTotalBytes()
Возвращает Integer
- Общий размер элемента загрузки в байтах.
Если размер неизвестен, он возвращает 0.
downloadItem.getReceivedBytes()
Возвращает Integer
- Полученные байты элемента загрузки.
downloadItem.getPercentComplete()
Returns Integer
- The download completion in percent.
downloadItem.getContentDisposition()
Возвращает string
- Поле Content-Disposition из заголовка ответа.
downloadItem.getState()
Returns string
- The current state. Can be progressing
, completed
, cancelled
or interrupted
.
[!NOTE] The following methods are useful specifically to resume a
cancelled
item when session is restarted.
downloadItem.getURLChain()
Возвращает string[]
- полная URL-цепочка до элемента, включая любые перенаправления.
downloadItem.getLastModifiedTime()
Возвращает string
- Последнее измененное значение заголовка.
downloadItem.getETag()
Возвращает string
- значение ETag заголовка.
downloadItem.getStartTime()
Возвращает Double
- Количество секунд с начала UNIX, когда началась загрузка.
downloadItem.getEndTime()
Returns Double
- Number of seconds since the UNIX epoch when the download ended.
Свойства экземпляра
downloadItem.savePath
Свойство string
, которое определяет путь к файлу сохранения элемента загрузки.
Свойство доступно только в сессии will-download
функции обратного вызова. Если пользователь не устанавливает путь сохранения через свойство, Electron будет использовать исходную процедуру для определения пути сохранения; здесь обычно вызывается диалоговое окно сохранения.