34

如果用户单击可下载的链接,例如

<a href="downloadable.txt">Download</a>

在“另存为”对话框之前是否有客户端(html 或 javascript)方法来更改文件的名称?

4

3 回答 3

97

HTML5 提供了a[download]允许您重命名文件的属性。此示例将下载link.txt并重命名它something.txt

​&lt;a download="something.txt" href="link.txt">asdf</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​

请注意,这仅适用于同源 URL(即不能跨不同域)。

于 2012-04-06T21:16:00.773 回答
18

不,您不能从客户端(HTML 或 javascript)更改此设置。您需要从服务器更改它。一种方法是使用将设置 Content-Disposition HTTP 响应标头的服务器端脚本:

Content-Disposition: attachment; filename=somecustomname.txt
于 2012-04-06T21:08:04.773 回答
4

您可以使用由 eligrey 编写的 Filesaver.js 脚本(我在此处的示例中使用 angularjs)您可以使用 XmlHttpRequest 对象在经典 javascript 中实现相同的功能

//In your html code , add these : ->
<script src="https://rawgit.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-animate.js"></script>
//In your Javascript:- 

$http({
        url: "url where the file is located",
        method: "GET",
        responseType: "blob"
    }).then(function (response) {

saveAs(response.data,"newfilename.extension");

})
于 2016-11-30T09:14:25.910 回答