1

Right now Im creating a website that gets the href from another page that contains all of our data. however instead of downloading the .dat file when I click the link, it just opens it in the current tab or a new tab as plain text.

this is the line of code that I am using

<a href='https://www.[I dont want to put the actual web address]/$namehref' download>$size</a>

$namehref is just the name of the file that is to be downloaded.

this worked when we had a .tar file but doesnt want to work for files that can be open and read within the webpage itself.

j08691
  • 204,283
  • 31
  • 260
  • 272
Ian Dimitri
  • 43
  • 1
  • 3
  • 1
    Does this answer your question? [(HTML) Download a PDF file instead of opening them in browser when clicked](https://stackoverflow.com/questions/6794255/html-download-a-pdf-file-instead-of-opening-them-in-browser-when-clicked) – Kulshreshth K May 04 '20 at 17:11

1 Answers1

1

You want to specify the file type and name when using HTML5 download attribute.

<a href="download/acme.txt" download="Acme.txt">Download Text</a>

Edit - File,type and name are optional fields. This will only work for files in relative directories. As of Chrome 65, Downloads from cross origin resources will ignore the html 5 attribute.

Better alternative will be to use a small Js function to force download the file on your behalf.

function forceDown(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();
    });
  });
}
<a href="#" onclick="forceDown('https://loremipsum.de/downloads/original.txt','original.txt');">Click here</a>

Make sure to include Access-Control-Allow-Origin in header of resource server.

AACaN
  • 90
  • 2
  • 8
  • Providing a filename is optional. The code in the question doesn't work because it is a cross-origin request. – Quentin May 04 '20 at 17:25
  • I stand corrected. According to this [question](https://stackoverflow.com/questions/26921024/html5-download-attribute-not-working-cross-domain-can-it-be-made-to-work) only firefox will enforce it. – AACaN May 04 '20 at 17:32
  • That was true in 2015. Chrome added the same security restriction to the download attribute soon after. – Quentin May 04 '20 at 17:33
  • Yes sorry, Updated my answer. – AACaN May 04 '20 at 18:31
  • This throws cors issues. and adding `{method: 'GET', mode: 'no-cors' }`to the fetch request creates a corrupted image of 0 bytes. – Timar Ivo Batis Feb 15 '23 at 08:04