电子和快递下载文件时的进度条

时间:2019-04-22 10:50:16

标签: javascript node.js express electron

我从this post中检索了此代码,但是,当我使用此代码时,出现此错误

Attempting to call a function in a renderer window that has been closed or released. Function provided here: :127:28

在第127行:session.defaultSession.on('will-download', function (event, downloadItem, webContents) {

开始下载时,它会显示错误消息,指出文件为空,但我的文件不为空

下载文件时进度条显示为0%


在EJS文件中

function sendURL(URL, format) {
    let tile = "<%= title %>"
    tit = tile.replace(/[`~!@#$^&'",.<>\{\}\[\]\\\/]/gi, '')
    window.location.href = `/download?URL=${URL}&title=${tit}&format=${format}`
}

[... More code ...]

const {session} = require('electron').remote

session.defaultSession.on('will-download', function (event, downloadItem, webContents) {
    "use strict";

    if (downloadItem.getTotalBytes() === 0) {
        swal({
            position: 'center',
            type: 'error',
            title: 'Fichier vide !',
            showConfirmButton: true,
            icon: "warning"
        })
    }

    downloadItem.on('updated', function (event, state) {
    process.stdout.write(downloadItem.getTotalBytes())
        if (state === 'interrupted') {
            swal({
                position: 'center',
                type: 'error',
                title: 'Téléchargement interrompu',
                showConfirmButton: true,
                icon: "info",
            })
        } else if (state === 'progressing') {
            let jQueryprogress = $(".progress")
            let jQuerybar = $(".progress__bar")
            let jQuerytext = $(".progress__text")
            let percent = 0
            let update
            let resetColors
            let speed = 200
            let orange = 30
            let yellow = 55
            let green = 85
            let timer

            resetColors = function () {
                jQuerybar
                    .removeClass("progress__bar--green")
                    .removeClass("progress__bar--yellow")
                    .removeClass("progress__bar--orange")
                    .removeClass("progress__bar--blue")

                jQueryprogress
                    .removeClass("progress--complete")

            }

            update = function () {
                timer = setTimeout(function () {
                    try {
                        let percentage = downloadItem.getReceivedBytes() / downloadItem.getTotalBytes()
                        percent = percentage * 100
                        percent = parseFloat(percent.toFixed(2))
                        update()
                    } catch (error) {
                        clearTimeout(timer)
                        percent = 100
                        resetColors()
                        jQueryprogress.addClass("progress--complete")
                        jQuerybar.addClass("progress__bar--blue")
                        jQuerytext.find("em").text("Complete")
                        percent = 0
                    }

                    jQuerytext.find("em").text(percent + "%")

                    if (downloadItem.isPaused()) jQuerytext.find("span").text('En pause')
                    else jQuerytext.find("span").text(downloadItem.getFilename())

                    if (percent >= green) {
                        jQuerybar.addClass("progress__bar--green")
                    }

                    else if (percent >= yellow) {
                        jQuerybar.addClass("progress__bar--yellow")
                    }

                    else if (percent >= orange) {
                        jQuerybar.addClass("progress__bar--orange")
                    }

                    speed = Math.floor(Math.random() * 100)

                    jQuerybar.css({ width: percent + " %" })

                }, speed)

            }

            $(".itemDL").addClass('bcenter')
            jQueryprogress.addClass("progress--active")
            update()
            resetColors()
        }

    })
    downloadItem.once('done', function (event, state) {

        console.log("Inside download done function " + event + state)

        if (state === 'completed') {
            setTimeout(function () {

                $(".itemDL").removeClass("bcenter")
                swal({
                    position: 'center',
                    type: 'success',
                    title: 'Téléchargement terminé',
                    showConfirmButton: true,
                    icon: "success",
                })

            }, 50)

        } else if (state === 'cancelled' || state === "interrupted") {
            $(".itemDL").removeClass("bcenter")
            swal({
                position: 'center',
                type: 'error',
                title: 'Téléchargement annulé ou interrompu',
                showConfirmButton: true,
                icon: "error",
            })
        } else {
            $(".itemDL").removeClass("bcenter")
            swal({
                position: 'center',
                type: 'error',
                title: 'Téléchargement échoué',
                showConfirmButton: true,
                icon: "error"
            })

        }
    })

    session.defaultSession.clearStorageData([], function () { console.log(' cleared all storages after download ') })
    session.defaultSession.clearCache(function () { console.log('cleared all caches after download') })
})

在router.js中

expressApp.get('/download', async (req, res) => {
    let URL = req.query.URL
    let title = req.query.title
    let format = req.query.format

    res.header('Content-Disposition', `attachment; filename="${title}.${format}"`)

    await ytdl(URL, {
        format: format
    }).pipe(res)
})

0 个答案:

没有答案