166

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.

starball
  • 20,030
  • 7
  • 43
  • 238
zachguo
  • 6,200
  • 5
  • 30
  • 31

12 Answers12

145

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.

golopot
  • 10,726
  • 6
  • 37
  • 51
Lucas Matos
  • 2,531
  • 2
  • 15
  • 17
  • 10
    is there any way to set the file name? – Anton Feb 05 '20 at 19:58
  • 6
    Yes, you can add Content-Disposition to the Headers obj, here is the documentation https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition – Lucas Matos Feb 07 '20 at 01: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 May 29 '20 at 23:35
  • This https://gist.github.com/devloco/5f779216c988438777b76e7db113d05c shows the full monty. – Dejan Jul 03 '20 at 22:34
  • This only opens the file in the same tab for me (using Chrome), does not download the file. – Tobias Ingebrigt Ørstad Mar 25 '21 at 19:33
  • Hello @TobiasIngebrigtØrstad can you share your code to review deeper the issue? – Lucas Matos Mar 26 '21 at 22:39
  • Hello Lucas, your code working good, downloading a file with random name. I've tried to add headers, but no luck at all. https://stackoverflow.com/questions/67767954/set-the-filename-for-file-download-with-use-of-fetch . Could you please head up to this? – noszone May 31 '21 at 06:37
  • @noszone Here is the documentation, about how to capture headers on the fetch response https://developer.mozilla.org/en-US/docs/Web/API/Response/headers – Lucas Matos May 31 '21 at 16:41
  • 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 Aug 05 '21 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 Nov 16 '21 at 08:42
  • 1
    For anyone coming here, check this: https://stackoverflow.com/a/56923508 – niaher Jul 05 '22 at 09:48
  • It does not work! it refreshes my page. – Nicolas S.Xu Jan 18 '23 at 21:00
  • `Content-Disposition` is not a [safe header](https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header). So I think you have to [expose it first](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers), then read it, then manually put it in the `download` attribute using the append anchor way. – Minh Nghĩa Aug 24 '23 at 06:01
132

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 library for that.


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

But based on this answer you can use createObjectURL to make 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         
        });
    });
messerbill
  • 5,499
  • 1
  • 27
  • 38
Mariusz Pawelski
  • 25,983
  • 11
  • 67
  • 80
  • @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 Oct 05 '18 at 13:09
  • 4
    It makes sense to call URL.revokeObjectURL in the end to avoid a memory leak. – Andrew Simontsev May 03 '19 at 06: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 Jul 11 '19 at 15:51
  • 9
    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. – aggregate1166877 Aug 27 '20 at 01:28
  • Also looking at the code on downloadjs, they use the same method of a temp to save the file. So the library doesn't necessarily do it a better way. – Joey Carlisle Sep 24 '21 at 16:09
  • This code seems to change the URL of the page? – evolutionxbox Nov 26 '21 at 21:36
  • not sure why, but i'm not getting the same binary as going directly to the URL ( i'm testing on an excel file ) direct URL in the browser -> open w/o a warning in Excel, and via fetch - raise a warning that it might be corrupted (?) ( clicking "Yes" to load it anyway - is loading it OK with all the data ... ) – Ricky Levi May 18 '22 at 09:13
65

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.

zachguo
  • 6,200
  • 5
  • 30
  • 31
  • 12
    just bear in mind the current blob size limit is around 500mb for browsers – tarikakyol Jan 26 '17 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 Apr 18 '19 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 Nov 16 '21 at 07: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 Apr 21 '22 at 06:26
  • Update on blob size limit: it's [2GB for desktop](https://chromium.googlesource.com/chromium/src/+/HEAD/storage/browser/blob/README.md#blob-storage-limits) in 2022 – Minh Nghĩa Nov 08 '22 at 08:18
22

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");
Zibri
  • 9,096
  • 3
  • 52
  • 44
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");
    });
};
Daniel
  • 343
  • 1
  • 4
  • 7
  • This mostly worked, but I ended up using the regex [from this other answer](https://stackoverflow.com/a/40940790/353145) instead. So... `fileName = fileName.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1] ? fileName.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1] : fileName;` – thargenediad May 29 '19 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 Nov 27 '19 at 22:51
  • This mostly works. Except Apple is behind times and your regex fails on Safari. :( aizquier's answer works. – Mmm Aug 24 '21 at 23:24
6

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)
}
Michael Hobbs
  • 1,663
  • 1
  • 15
  • 26
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
Yuci
  • 27,235
  • 10
  • 114
  • 113
  • how could you make the CSS above Inline in the HTML? – JeffR Dec 16 '20 at 01:01
  • 1
    @JeffR, it would like something like this: `Download`, and the `class` attribute here is only for querySelector to use in the JS code. – Yuci Dec 16 '20 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 Dec 16 '20 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 Dec 16 '20 at 16:08
3

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.

3

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)

lemonskunnk
  • 296
  • 1
  • 12
  • 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 Aug 10 '21 at 23:18
3

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();
}
mustafa candan
  • 567
  • 5
  • 16
0

I guess the correct today answer is

fetch(window.location).then(async res=>res.body.pipeTo(await (await showSaveFilePicker({
  suggestedName: 'Any-suggestedName.txt'
})).createWritable()));
frank-dspeed
  • 942
  • 11
  • 29
0

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.

noraj
  • 3,964
  • 1
  • 30
  • 38