Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

javascript - AJAX download file from Express results in "this site attempted to download multiple files" (Chrome)

Why is this so convoluted? I want to download a file and I get this error:

this site attempted to download multiple files

How can I prevent this error and actually download the file?

If I disable the block, it works fine... But It's really bad UX to have the client do this.

what is it that I am triggering here, as I only download a single file?

I am using the svelte framework, if it changes anything.

client

async function downloadFile(fieldId, fileName) {
        let response = await fetchGetFile(`/api/files/${fieldId}`);
        let blob = await response.blob();
        let url = window.URL.createObjectURL(blob);

        let a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        a.download = fileName;

        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
    }

server

router.get("/api/files/:fileId", async (req, res, next) => {
    try {
        let { fileId } = req.params;

        let query = `
            select *
            from file
            where id = ?
        `;

        let rows = await req.asyncQuery(query, [fileId]);

        let data = rows[0];

        let file = path.join(__dirname, `/../uploads/${data.fileName}`);

        res.download(file);
    } catch (err) {
        next(err);
    } finally {
        req.connection.release();
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...