close

How can I download a file using window.fetch?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How can I download a file using window.fetch? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How can I download a file using window.fetch ?

  1. How can I download a file using window.fetch ?

    can I download a file using window.fetch now i just change window.location.href and add query params like the jsonwebtoken and other stuff.

  2. can I download a file using window.fetch

    can I download a file using window.fetch now i just change window.location.href and add query params like the jsonwebtoken and other stuff.

Method 1

Using dowloadjs. This will parse the filename from the header.

fetch("yourURL", {
    method: "POST",
    body: JSON.stringify(search),
    headers: {
        "Content-Type": "application/json; charset=utf-8"
    }
    })
    .then(response => {
        if (response.status === 200) {
            filename = response.headers.get("content-disposition");
            filename = filename.match(/(?<=")(?:\\.|[^"\\])*(?=")/)[0];
            return response.blob();
        } else {
        return;
        }
    })
    .then(body => {
        download(body, filename, "application/octet-stream");
    });
};

Method 2

I tried window.fetch but that ended up being complicated with my REACT app

now i just change window.location.href and add query params like the jsonwebtoken and other stuff.

///==== client side code =====
var url = new URL(`http://${process.env.REACT_APP_URL}/api/mix-sheets/list`);
url.searchParams.append("interval",data.interval);
url.searchParams.append("jwt",token)

window.location.href=url;

// ===== server side code =====

// on the server i set the content disposition to a file
var list = encodeToCsv(dataToEncode);
res.set({"Content-Disposition":`attachment; filename=\"FileName.csv\"`});
res.status(200).send(list)

the end results actually end up being pretty nice, the window makes request and downloads the file and doesn’t event switch move the page away, its as if the window.location.href call was like a lowkey fetch() call.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment