我得到了一些代码off of here,我尝试使用它,但是当我尝试使用它时,它并没有像我预期的那样工作。你能帮助修复代码,以便出现一个对话框来保存文件,而不是自动下载。它可能只需要对函数进行微调......
这是HTML ...
<table>
<tr><td>Text to Save:</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad">
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
</table>
和Javascript ......
function saveTextAsFile() {
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null) {
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
function loadFileAsText() {
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
编辑:这个问题很独特,因为我不是在问如何强制下载,我问的是如何打开“另存为”#39;对话框,如保存图像时显示的对话框
编辑:ActiveX可能有这个答案吗?
编辑:似乎无法用ActiveX执行此操作,但程序仍然有一个文件名框。为什么程序会忽略它?下载的文件名是(看起来像什么)随机生成的数字?答案 0 :(得分:-1)
如果您要求获得传统的“另存为...”对话框,则无法通过JavaScript。浏览器根据默认设置下载文件,默认设置可能是默认下载位置,也可能提供对话框,但这又取决于客户端的设置,而不是JavaScript。