简体   繁体   中英

How to download a file in jquery

I am sending a ajax request on click of LINK from there i am getting a URL of PDF file now after getting the response i want to download that particular file on user's system.But i am not able to download that particular file on user system.It is getting opened on the browser url, i don't want to show the url of PDF file to the user.How can we do this in jquery.

HTML

<li><a href="javascript:void(0)" data-unid ="1" class ="cert_download">Download</a></li>

Jquery

$.ajax({
    type:"POST",
    url: myurl,
    dataType: "json",
    data:data,
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert("There is some problem in our system please try after sometimes");
    },
    success: function(data){
        if(data.url){
            if (!window.location.origin){
                window.location.origin = window.location.protocol+"//"+window.location.host+"/";
                location.href = window.location.origin+data.url;
            }
        }
    }
});

I don't want to show user the URL and even i don't want to download the file in a new tab/window.As he click on link i want to download the file to his sytem How can we download the file to the user.Please help me in this

This will work for u :

function downloadURI(uri, name){
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    $("#data_cert").html(link);
    link.click();
    $("#data_cert").html("");
}

Just open new window with

window.open('link to pdf', '_blank')

And send the pdf with

header('Content-Disposition: attachment; filename=some.pdf')

Window will close as soon someone click download.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM