我正在从下面的代码中使用HTML5下载文件,您可以在 JSBINHTML5上实时查看运行情况。下载文件DEMO 及其工作正常,并在浏览器默认的“ 下载文件夹”中下载文件 。
<!DOCTYPE html> <html> </head> </head> <body> <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"></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> <td><button onclick="loadFileAsText()">Load Selected File</button><td> </tr> </table> <script type='text/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"); } </script> </body> </html>
但我想在其他位置下载它。就像我离线使用此代码一样,只在index.html文件中包含上部代码。当我从浏览器运行此文件时,file:///C:/Users/Public/Desktop/它将下载该文件并将其保存在file:///C:/Users/Public/Downloads/。因此,我想从调用它的位置下载此文件。为此,我从以下代码中选择路径。它给了我这样的路径,/C:/Users/Public/Desktop/所以我想在这里保存文件。无论我index.html将这个文件放到哪里,它都会下载该文件并将其保存在index.html文件中。这怎么可能?
index.html
file:///C:/Users/Public/Desktop/
file:///C:/Users/Public/Downloads/
/C:/Users/Public/Desktop/
var url = window.location.pathname; var folderpath = url.substring(0,url.lastIndexOf('/')+1); alert(folderpath);
这是不可能的,因为这带来了安全风险。人们在其文件夹结构中使用了相当真实的信息,访问文件夹名称本身就构成了直接风险。
大多数操作系统倾向于仅默认为下载位置,这是用户通过使用的浏览器决定的。不是网站。