184

If I want to download a file, what should I do in the then block below?

function downloadFile(token, fileId) {
  let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Authorization': token
    }
  }).then(...);
}

Note: The code is on the client-side.

4
  • 1
    What about adding a download attribute to a link which has the URL https://www.googleapis.com/drive/v2/files/${fileId}?alt=media
    – Arjun
    Commented Sep 13, 2015 at 2:42
  • 2
    @Arjun how do you add the token to the header of your request?
    – anhtv13
    Commented May 12, 2020 at 7:20
  • @anhtv13 I'm sorry, I don't understand your question. With my original comment, the solution I was suggesting was to create an <a> element with a download attribute and simulating a click on that element, all with the use of JavaScript. See Zibri's answer (which, btw, was posted way after my comment).
    – Arjun
    Commented May 13, 2020 at 9:45
  • 2
    the api is secure, you can't just go to the url and download, need to pass a token to the header. Something like"'Authorization":"Bearer" + <token>. In this situation how do you add the token to the header?
    – anhtv13
    Commented May 13, 2020 at 9:52

12 Answers 12

171

This is more shorter and efficient, no libraries only fetch API

const url ='http://sample.example.file.doc'
const authHeader ="Bearer 6Q************" 

const options = {
  headers: {
    Authorization: authHeader
  }
};
 fetch(url, options)
  .then( res => res.blob() )
  .then( blob => {
    var file = window.URL.createObjectURL(blob);
    window.location.assign(file);
  });

This solution does not allow you to change filename for the downloaded file. The filename will be a random uuid.

13
  • 13
    is there any way to set the file name?
    – Anton
    Commented Feb 5, 2020 at 19:58
  • 7
    Yes, you can add Content-Disposition to the Headers obj, here is the documentation developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… Commented Feb 7, 2020 at 1:22
  • 5
    @LucasMatos I added “Content-Disposition” header to options object and I do get the correct header for my file when inspecting it in network tab, but then the blob is created and the name is thrown away so I end up with a generated random name. Do you know how to pass the name to blob with your solution?
    – miran80
    Commented May 29, 2020 at 23:35
  • 6
    @LucasMatos I tried editing your answer but the queue is full. In order to assert a name to the file being downloaded is to add an extra line: var file = new File([blob], "filename.extension"); file = window.URL.createObjectURL(file);
    – luke_16
    Commented Aug 5, 2021 at 20:15
  • 6
    @luke_16 your suggestion didn't work for me: what worked but without setting filename is const fileUrl = window.URL.createObjectURL(blob); window.location.assign(fileUrl), but when I modified it to const file = new File([blob], fileName); const fileUrl = window.URL.createObjectURL(file); window.location.assign(fileUrl), I get browser trying to display the binary on a different url (like blob:blob://http://localhost:8070/7174db61-b974-44fb-8a15-946f400378d0). Any ideas what's wrong with it?
    – YakovL
    Commented Nov 16, 2021 at 8:42
139

EDIT: syg answer is better. Just use downloadjs library.

The answer I provided works well on Chrome, but on Firefox and IE you need some different variant of this code. It's better to use this library for that.


I had similar problem (need to pass authorization header to download a file so this solution didn't help).

But based on this answer, you can use createObjectURL to make your browser save a file downloaded by Fetch API.

getAuthToken()
    .then(token => {
        fetch("http://example.com/ExportExcel", {
            method: 'GET',
            headers: new Headers({
                "Authorization": "Bearer " + token
            })
        })
        .then(response => response.blob())
        .then(blob => {
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = "filename.xlsx";
            document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
            a.click();    
            a.remove();  //afterwards we remove the element again         
        });
    });
7
  • @David I updated the answer. Should now also work in FF. The problem was, that FF wants the link element to be appended to the DOM. This is not mandatory in Chrome or Safari.
    – messerbill
    Commented Oct 5, 2018 at 13:09
  • 5
    It makes sense to call URL.revokeObjectURL in the end to avoid a memory leak. Commented May 3, 2019 at 6:34
  • @AndrewSimontsev Great tip, thanks for the input! I edited the response, let me know if it is correct that way. Tested on my code and seems ok!
    – jbarradas
    Commented Jul 11, 2019 at 15:51
  • 12
    I disagree that using a library is a better answer :). Using external libraries is not always an option, and when it is, then finding libraries is easy. It's not answer worthy, which is likely why your answer has more votes than the accepted answer despite the accepted being 2 years older. Commented Aug 27, 2020 at 1:28
  • 2
    Also looking at the code on downloadjs, they use the same method of a temp <a/> to save the file. So the library doesn't necessarily do it a better way. Commented Sep 24, 2021 at 16:09
66

I temporarily solve this problem by using download.js and blob.

let download = require('./download.min');

...

function downloadFile(token, fileId) {
  let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Authorization': token
    }
  }).then(function(resp) {
    return resp.blob();
  }).then(function(blob) {
    download(blob);
  });
}

It's working for small files, but maybe not working for large files. I think I should dig Stream more.

6
  • 12
    just bear in mind the current blob size limit is around 500mb for browsers
    – tarikakyol
    Commented Jan 26, 2017 at 13:45
  • Nice, just one thing: would it be possible to get the file name from the server response so to let the user download it with its real name?
    – Phate
    Commented Apr 18, 2019 at 14:58
  • @Phate to do so, you should pass an object from server, which contains not only the data but also the name. Once you do that, you can deal with its field separately, but for that you should see other answers here as (as far as I understand) .blob method is specific one of object which fetch resolves with
    – YakovL
    Commented Nov 16, 2021 at 7:48
  • You need a node plugin that can resolve require -see first line - on the client side, such as bundler.js and make the download package available.
    – Timo
    Commented Apr 21, 2022 at 6:26
  • Update on blob size limit: it's 2GB for desktop in 2022 Commented Nov 8, 2022 at 8:18
24

function download(dataurl, filename) {
  var a = document.createElement("a");
  a.href = dataurl;
  a.setAttribute("download", filename);
  a.click();
  return false;
}

download("data:text/html,HelloWorld!", "helloWorld.txt");

or:

function download(url, filename) {
fetch(url).then(function(t) {
    return t.blob().then((b)=>{
        var a = document.createElement("a");
        a.href = URL.createObjectURL(b);
        a.setAttribute("download", filename);
        a.click();
    }
    );
});
}

download("https://get.geojs.io/v1/ip/geo.json","geoip.json")
download("data:text/html,HelloWorld!", "helloWorld.txt");

9

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");
    });
};
3
  • This mostly worked, but I ended up using the regex from this other answer instead. So... fileName = fileName.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1] ? fileName.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1] : fileName; Commented May 29, 2019 at 10:47
  • 3
    Firefox does not support filename.match(), I replaced that part with: filename = response.headers.get("content-disposition").split(";")[1].split('"')[1]; . Besides, the server must declare the header Access-Control-Expose-Headers: Content-Disposition in order to allow the browser to read the content-disposition header.
    – aizquier
    Commented Nov 27, 2019 at 22:51
  • This mostly works. Except Apple is behind times and your regex fails on Safari. :( aizquier's answer works.
    – Mmm
    Commented Aug 24, 2021 at 23:24
7

Here is an example using node-fetch for anyone that finds this.

reportRunner({url, params = {}}) {
    let urlWithParams = `${url}?`
    Object.keys(params).forEach((key) => urlWithParams += `&${key}=${params[key]}`)
    return fetch(urlWithParams)
        .then(async res => ({
            filename: res.headers.get('content-disposition').split('filename=')[1],
            blob: await res.blob()
        }))
        .catch(this.handleError)
}
3
  • Where does this save it to? @Michael Hobbs
    – FabricioG
    Commented Mar 14, 2019 at 6:15
  • The function returns an object {filename, blob}, you can use fs.writefile to save the file to disk. Commented Mar 14, 2019 at 16:19
  • 1
    probably one of the rare examples that shows how to get download filename & type
    – Mahesh
    Commented Sep 27, 2022 at 13:56
6

As per some of the other answers, you can definitely use window.fetch and download.js to download a file. However, using window.fetch with blob has the restriction on memory imposed by the browser, and the download.js also has its compatibility restrictions.

If you need to download a big-sized file, you don't want to put it in the memory of the client side to stress the browser, right? Instead, you probably prefer to download it via a stream. In such a case, using an HTML link to download a file is one of the best/simplest ways, especially for downloading big-sized files via a stream.

Step One: create and style a link element

You can make the link invisible but still actionable.

HTML:

<a href="#" class="download-link" download>Download</a>

CSS:

.download-link {
  position: absolute;
  top: -9999px;
  left: -9999px;
  opacity: 0;
}

Step Two: Set the href of the link, and trigger the click event

JavaScript

let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;

const downloadLink = document.querySelector('.download-link')
downloadLink.href = url + '&ts=' + new Date().getTime() // Prevent cache
downloadLink.click()

Notes:

  • You can dynamically generate the link element if necessary.
  • This approach is especially useful for downloading, via a stream, big-sized files that are dynamically generated on the server side
4
  • how could you make the CSS above Inline in the HTML?
    – JeffR
    Commented Dec 16, 2020 at 1:01
  • 1
    @JeffR, it would like something like this: <a href="#" class="download-link" style="position: absolute; top: -9999px; left: -9999px; opacity: 0" download>Download</a>, and the class attribute here is only for querySelector to use in the JS code.
    – Yuci
    Commented Dec 16, 2020 at 10:07
  • When I execute the line 'downloadLink.click()', the rest of my HTML code disappears. Any reason for that? If I comment the 'downloadLink.click()' out and instead show the Download link, all html works fine. Any ideas?
    – JeffR
    Commented Dec 16, 2020 at 12:49
  • @JeffR Maybe something to do with the download attribute of the a HTML element. This attribute instructs browsers to download a URL instead of navigating to it, so the user will be prompted to save it as a local file. This attribute only works for same-origin URLs. Also try without the '&ts=' + new Date().getTime() part, to see if it makes any difference to your case.
    – Yuci
    Commented Dec 16, 2020 at 16:08
6

No libraries only fetch API. Also you can change the file name

function myFetch(textParam, typeParam) {
  fetch("http://localhost:8000/api", {
    method: "POST",
    headers: {
      Accept: "application/json, text/plain, */*",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      text: textParam,
      barcode_type_selection: typeParam,
    }),
  })
    .then((response) => {
      return response.blob();
    })
    .then((blob) => {
      downloadFile(blob);
    });
}

Here is the download file function

function downloadFile(blob, name = "file.pdf") {
  const href = URL.createObjectURL(blob);
  const a = Object.assign(document.createElement("a"), {
    href,
    style: "display:none",
    download: name,
  });
  document.body.appendChild(a);
  a.click();
  URL.revokeObjectURL(href);
  a.remove();
}
5

A similar but cleaner and more reliable solution IMO.

On your fetch function...

fetch(...)    
.then(res => 
    {
        //you may want to add some validation here
        downloadFile(res);
    }
)

and the downloadFile function is...

async function downloadFile(fetchResult) {        
    var filename = fetchResult.headers.get('content-disposition').split('filename=')[1];
    var data = await fetchResult.blob();
    // It is necessary to create a new blob object with mime-type explicitly set
    // otherwise only Chrome works like it should
    const blob = new Blob([data], { type: data.type || 'application/octet-stream' });
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // IE doesn't allow using a blob object directly as link href.
        // Workaround for "HTML7007: One or more blob URLs were
        // revoked by closing the blob for which they were created.
        // These URLs will no longer resolve as the data backing
        // the URL has been freed."
        window.navigator.msSaveBlob(blob, filename);
        return;
    }
    // Other browsers
    // Create a link pointing to the ObjectURL containing the blob
    const blobURL = window.URL.createObjectURL(blob);
    const tempLink = document.createElement('a');
    tempLink.style.display = 'none';
    tempLink.href = blobURL;
    tempLink.setAttribute('download', filename);
    // Safari thinks _blank anchor are pop ups. We only want to set _blank
    // target if the browser does not support the HTML5 download attribute.
    // This allows you to download files in desktop safari if pop up blocking
    // is enabled.
    if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank');
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    setTimeout(() => {
        // For Firefox it is necessary to delay revoking the ObjectURL
        window.URL.revokeObjectURL(blobURL);
    }, 100);
}

(downloadFile function source: https://gist.github.com/davalapar/d0a5ba7cce4bc599f54800da22926da2)

1
  • This is a helpful solution, thanks! As written the filename value comes through twice in filename. Changing the first line of downloadFile to var filename = fetchResult.headers.get('content-disposition').split('filename=')[1].split(';')[0].slice(1, -1); to strip off the second part (UTF/percent encoded) and the leading and trailing quotation marks works perfectly for me. (Assuming no semicolon in the filename!)
    – Mmm
    Commented Aug 10, 2021 at 23:18
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.

2

This is Lucas Matos answer (no libraries only fetch API) but with support for a custom name.

const url ='http://sample.example.file.doc'
const authHeader ="Bearer 6Q************" 

const options = {
  headers: {
    Authorization: authHeader
  }
};
 fetch(url, options)
  .then( res => res.blob() )
  .then( blob => {
    var fileURL = URL.createObjectURL(blob);
    var fileLink = document.createElement('a');
    fileLink.href = fileURL;
    fileLink.download = `whatever.ext`;
    fileLink.click();
  });

This solution does not allow you to change filename for the downloaded file. The filename will be a random uuid.

1

I guess the correct today answer is

fetch(window.location).then(async res=>res.body.pipeTo(await (await showSaveFilePicker({
  suggestedName: 'Any-suggestedName.txt'
})).createWritable()));
2
  • I get "ReferenceError: showSaveFilePicker is not defined"
    – Paul Heil
    Commented Jul 6, 2023 at 15:13
  • showSaveFilePicker has very limited browser support still
    – jonlink
    Commented Sep 13, 2023 at 21:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.