Prompting user to save file using a 'Save-as' dialog?

无人久伴 提交于 2019-11-30 04:37:37

问题


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.

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.

A quick simple reply would be really appreciated.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19679842/prompting-user-to-save-file-using-a-save-as-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!