Download File Using Javascript/jQuery

前端 未结 28 2968
悲&欢浪女
悲&欢浪女 2020-11-21 05:11

I have a very similar requirement specified here.

I need to have the user\'s browser start a download manually when $(\'a#someID\').click();

But

28条回答
  •  青春惊慌失措
    2020-11-21 05:53

    let args = {"data":htmlData,"filename":exampleName}
    

    To create a HTMl file and download

    window.downloadHTML = function(args) {
    var data, filename, link;
    var csv = args.data;
    if (csv == null) return;
    filename = args.filename || 'report.html';
    data = 'data:text/html;charset=utf-8,' + encodeURIComponent(csv);
    console.log(data);
    link = document.createElement('a');
    link.setAttribute('href', data);
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);}
    

    To create and download a CSV

    window.downloadCSV = function(args) {
    var data, filename, link;
    var csv = args.data;
    if (csv == null) return;
    filename = args.filename || 'report.csv';
    if (!csv.match(/^data:text\/csv/i)) {
        csv = 'data:text/csv;charset=utf-8,' + csv;
    }
    data = encodeURI(csv);
    link = document.createElement('a');
    link.setAttribute('href', data);
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    

    }

提交回复
热议问题