Javascript 在javascript中更改下载名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10049259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change name of download in javascript
提问by Intra
If a user clicks on a downloadable link such as
如果用户单击可下载的链接,例如
<a href="downloadable.txt">Download</a>
Is there a client-side (html or javascript) way to change the name of the file before the 'Save As' dialog?
是否有客户端(html 或 javascript)方法可以在“另存为”对话框之前更改文件名?
采纳答案by Darin Dimitrov
No, you cannot change this from the client side (HTML or javascript). You need to change it from the server. One way is to use a server side script which will set the Content-Disposition HTTP response header:
不,您不能从客户端(HTML 或 javascript)更改此设置。您需要从服务器更改它。一种方法是使用服务器端脚本来设置 Content-Disposition HTTP 响应头:
Content-Disposition: attachment; filename=somecustomname.txt
回答by Dennis
HTML5 provides the a[download]
attribute which lets you rename a file. This example will download link.txt
and rename it something.txt
.
HTML5 提供了a[download]
让您重命名文件的属性。此示例将下载link.txt
并重命名它something.txt
。
?<a download="something.txt" href="link.txt">asdf</a>???????????????????????????
Note that this only works on same-origin URLs (i.e. not across different domains).
请注意,这仅适用于同源 URL(即不能跨越不同域)。
回答by Vibhu
You can use Filesaver.js script written by eligrey(Im using angularjs in the example here) You can achieve the same in classic javascript using XmlHttpRequest object
您可以使用 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");
})