簡體   English   中英

后端的 ExpressJS res.download() + 前端的 fetch

[英]ExpressJS res.download() on backend + fetch on frontend

對不起,如果這是一個菜鳥問題,但我無法讓它工作......

我有一個使用 NodeJS 和 ExpressJs 並提供一些使用 VueJS 構建的 static 東西的后端。

我想允許用戶下載文件,所以我正在嘗試實現它。

在后端,這是代碼

    app.get('/download', function (req, res, next) {
    let queryparams = req.query;
    if (queryparams.filename) {
        try {
            res.download(queryparams.filename); 
        } catch (error) {
            console.log('Unable to read ' + queryparams.filename + ' file. Please check');
            res.write('Unable to read ' + queryparams.filename + ' file. Please check');
            res.status(501);

        }
        res.end();
    } else {
        next();
    }
});

在前端,我嘗試使用 downloadjs npm package 這但它不起作用,更進一步,我需要它嗎?

fetch(`https://${servername}/download?filename=` + data.filename)
    .then((response) => response.blob())
    .then((blob) => downloadjs(blob, data.filename));

任何幫助將不勝感激

鮑勃

這就是我在我的 express 應用程序上實現下載的方式。 當用戶訪問這個特定的 URL 時,他們會自動下載該文件。 這是我正在從事的項目的代碼片段。 希望能幫助到你

router.get('/frontliners/file.csv', function (req, res) {
    controller.airtableFrontliners((output) => {
        res.status(200)
        const file = `${__dirname}/data.csv`; // Get the path of the file
        res.download(file); 
    })
});

您缺少的是您嘗試下載的文件的路徑。

app.get('/download', function (req, res, next) {
    if (req.query.filename) {
        try {
            res.download(req.query.filename); 
        } catch (error) {
            console.log('Unable to read ' + req.query.filename + ' file. Please check');
            res.write('Unable to read ' + req.query.filename + ' file. Please check');
            res.status(501);
        }
        res.end();
    } else {
        next();
    }
});

如果我們在res.download(queryparams.filename)部分查看您的代碼,您會丟失將要下載的文件的相對路徑(如果您不知道,還有文件擴展名類型)。

假設我點擊這個 URL 就像: http://.../download/day1.json
該代碼會將其解釋為res.download("day1.json")正確,但它不知道在哪里查找該文件。

因此,如果您將其更改為res.download("./downloadables/day1.json")文件day1.json將下載,因為代碼可以導航到代碼根目錄中可下載目錄中的該文件。
進行如下所示的更改可以幫助您解決此問題。

app.get('/download', function (req, res, next) {
    if (req.query.filename) {
        try {
            // Adding ticks for string fomatting
            res.download(`./${req.query.filename}`); 
        } catch (error) {
            console.log('Unable to read ' + queryparams.filename + ' file. Please check');
            res.write('Unable to read ' + queryparams.filename + ' file. Please check');
            res.status(501);
        }
        res.end();
    } else {
        next();
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM