javascript 提示用户使用“另存为”对话框保存文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19679842/
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
Prompting user to save file using a 'Save-as' dialog?
提问by Abdul Jabbar
I currently have this code:
我目前有这个代码:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.click();
}
download('test.html', string);
The string
contains a lot of html code that gets written in an .html file.
The above code is working perfectly:
On a button click, the browser (chrome) automatically downloads an html file with the string content written in it.
在string
包含了很多的被写在一个.html文件的HTML代码。
上面的代码运行良好:单击按钮时,浏览器 (chrome) 会自动下载一个 html 文件,其中写入了字符串内容。
Now, what I want to do is, instead of chrome downloading the file automatically, it should open a "save-as" dialog box and ask the user the location and name of the file, and then download it to that location.
现在,我想要做的是,它应该打开一个“另存为”对话框并询问用户文件的位置和名称,然后将其下载到该位置,而不是 chrome 自动下载文件。
A quick simple reply would be really appreciated.
快速简单的答复将不胜感激。
采纳答案by Abdul Jabbar
My browser was set to automatically download all files in default location which is why not only this file but all other files from my browser were downloaded directly without the save prompt dialogue. Changing the settings in browser to 'always ask the download location' worked.
我的浏览器被设置为自动下载默认位置的所有文件,这就是为什么不仅这个文件而且我浏览器中的所有其他文件都直接下载而没有保存提示对话框。将浏览器中的设置更改为“始终询问下载位置”有效。
回答by sidonaldson
The only way to do this is to set the header of the file on the server, like so:
这样做的唯一方法是在服务器上设置文件的标题,如下所示:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
The download attribute does not allow you to change the filename or filetype any more as it is an obvious security risk.
下载属性不允许您再更改文件名或文件类型,因为这存在明显的安全风险。
What you are trying to do it replicate the right-click - save-as dialogue but I'm afraid that is not possible at this time.
您尝试执行的操作是复制右键单击 - 另存为对话框,但恐怕目前无法实现。