1

I have a function to download files:

downloadFile(url, filename) {
    var link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    link = null;
},

This function work with .csv and .xlsx files. When a user click to a button .txt file supposed to download too. If it is a txt file nothing happens.

I add this this two lines to code;

    if(url.includes(".txt")){
      link.target = '_blank';
    }

It looks like this;

downloadFile(url, filename) {
    var link = document.createElement('a');
    link.href = url;
    link.download = filename;
    if(url.includes(".txt")){
      link.target = '_blank';
    }
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    link = null;
},

When a user want to download the txt file it opens on a tab of browser and they need to right click and save the file over and over again.

For example this link; Example txt file

So how can I make the URL ending with .txt extension downloadable?

This solution tried but it is not link, it just content. Not Work

Murat Demir
  • 716
  • 7
  • 26
  • 1
    That code works just fine to download a `.txt` for me with Chrome and Firefox. – T.J. Crowder Mar 23 '22 at 12:19
  • I am trying on VUE.js but logics are same. Do you think it cause the problem? @T.J.Crowder – Murat Demir Mar 23 '22 at 12:22
  • I don't use Vue.js. Assuming it stays out of the way of the above, though, I would expect that to matter. (It wouldn't with React.) – T.J. Crowder Mar 23 '22 at 12:24
  • 1
    [JSFiddle](https://jsfiddle.net/nueagyv6/) I try here but result same. If operating system cause, users have windows, mac, linux. All have same feedback @T.J.Crowder. – Murat Demir Mar 23 '22 at 12:30
  • 2
    @MuratDemir [From MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a?retiredLocale=nl#attr-download) "_`download` only works for [same-origin URLs](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy), or the `blob:` and `data:` schemes_". Is your `url` on the same origin? – Ivar Mar 23 '22 at 12:39
  • check https://stackoverflow.com/questions/64998717/open-generated-text-as-savable-txt-file-in-new-tab – James Mar 23 '22 at 12:41
  • @Ivar No, it come from an api. – Murat Demir Mar 23 '22 at 12:44
  • Omg, it works well. Thank you @Ivar. You can write an answer, I will accept it. – Murat Demir Mar 23 '22 at 12:50
  • 1
    @MuratDemir [No need to repeat answers](https://stackoverflow.com/help/duplicates). :) You should have the option to accept the question as a duplicate. – Ivar Mar 23 '22 at 12:52

0 Answers0