Search code examples
javascriptjqueryhtmlhref

Use javascript variable as file name to download file with href


I have a javascript code that extracts filename as a variable from the current html file. The filename, for example, is "new.html" filename variable is successfully used to append href where I need to open same file strored in another folder. Using the same code, I need to append this variable to a folder path with href tag to download a file with href tag. The file name is extracted from .html (example new) and added to .xls file (example new.xls)

var filename=location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
console.log(filename); 
document.getElementById("htag1").href= "Foldername/"+filename; 
var object=filename.slice(0,-5);
var xls=".xls";
var xlsfile=object+xls;
$(".xlsfile").text(xlsfile); 
console.log(xlsfile);
document.getElementById("d1tag1").href= "Foldername/"+xlsfile; 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="htag1" target="_blank">#working</a>
<a href="#" id="d1tag1" target="_blank" download="">#not working</a>

<a href="Foldername/new.xls" target="_blank" download="new.xls">####working download code####</a>

But this is giving me download error with no file getting downloaded but it is pointing to the right path. Should I use another way for download feature? Before this I had entered the file path statically which seemed to work. Any help would be appreciated! Thank you!


Solution

  • Try this way, i'm sure now it will work ^^

    var filename=location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
    console.log(filename); 
    document.getElementById("htag1").href= "Foldername/"+filename; 
    var object=filename.split(".")[0];
    var xls=".xls";
    var xlsfile=object+xls;
    $(".xlsfile").text(xlsfile); 
    console.log(xlsfile);
    document.getElementById("d1tag1").href= "Foldername/"+xlsfile;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" id="htag1" target="_blank">#working</a>
    <a href="#" id="d1tag1" target="_blank" download="">#not working</a>
    
    <a href="Foldername/new.xls" target="_blank" download="new.xls">####working download code####</a>