在JavaScript中更改下载的名称

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

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

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

不,你不能从客户端(HTML或JavaScript)改变这一点。 您需要从服务器更改它。 一种方法是使用服务器端脚本来设置Content-Disposition HTTP响应头:

 Content-Disposition: attachment; filename=somecustomname.txt 

HTML5提供了a[download]属性,可让您重命名文件。 这个例子将下载link.txt并将其重命名为something.txt

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

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

您可以使用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"); })