Search code examples
htmlhyperlinkrelative-path

HTML <a> Link href Doesn't Work with "Embedded Spaces" in a "Relative Path"


I have searched everywhere I can think of and can't find a single example of an "a" href which contains a relative path on localhost with embedded spaces. I am trying to download a json file from my localhost located at "json/test file.json". If I rename the file to "json/test-file.json" then the link works fine. I have hundreds of json files and renaming them will break other applications. I have also tried putting quotes around 'json/test file.json' and that does not work either.

Here is a simple tag that demonstrates the problem

<a id="download_json" href="json/test%20file.json" title="Download JSON" target="new" download>Download</a>

I have already tried encodeURI but that is a waste of time. If you can just hard code the path/file as shown above for testing with nothing fancy it would be helpful and avoid distractions.

This problem must have a very simple solution, I just can't seem to put my finger on it.

Any ideas will be deeply appreciated, Thank you for your time.


Solution

  • Finally found the answer. Problem only with Firefox Developers Edition

    function downloadJSON(filename, dataObjToWrite){
      const blob = new Blob([JSON.stringify(dataObjToWrite)], { type: "text/json" });
      const link = document.createElement("a");
      link.download = filename;
      link.href = window.URL.createObjectURL(blob);
      link.dataset.downloadurl = ["text/json", link.download, link.href].join(":");
      const evt = new MouseEvent("click", {
            view: window,
            bubbles: true,
            cancelable: true,
      });
      link.dispatchEvent(evt);
      link.remove()
    };