如何在锚标记中指定数据URI资源的文件名?

时间:2014-05-24 21:37:27

标签: javascript html data-uri

我想使用javascript实现客户端可下载文件,并使用DATA URI以下列方式在客户端动态创建文件:

<a href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Download CSV</a>

但是,下载的文件没有名称。我在stackoverflow上看到了一些解决方案,其中包括&#39; download&#39;可以使用属性,但我需要支持旧的浏览器,所以我不能使用它。

3 个答案:

答案 0 :(得分:5)

您可以根据自己的需要轻松调整这段代码:

//Generate a file name
    var fileName = "List_";
    //this will remove the blank-spaces from the title and replace it with an underscore
    fileName += ReportTitle.replace(/ /g,"_");   

    //Initialize file format you want csv or xls
    var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

    // Now the little tricky part.
    // you can use either>> window.open(uri);
    // but this will not work in some browsers
    // or you will not get the correct file extension    

    //this trick will generate a temp <a /> tag
    var link = document.createElement("a");    
    link.href = uri;

    //set the visibility hidden so it will not effect on your web-layout
    link.style = "visibility:hidden";
    link.download = fileName + ".csv";

    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

答案 1 :(得分:1)

download标记的

a属性现在指定下载文件的名称:

https://html.spec.whatwg.org/multipage/semantics.html#attr-hyperlink-download

答案 2 :(得分:0)

看看以下链接。它似乎允许您下载客户端生成的数据并指定文件名。

https://code.google.com/p/download-data-uri/