使用 HTML5 在不同位置下载文件

IT技术 javascript html download
2021-01-15 11:26:22

我正在从下面的代码中使用 HTML5 下载文件,您可以在JSBIN HTML5 下载文件演示中看到实时运行及其完美运行的文件,并在我的浏览器默认下载文件夹中下载我的文件

<!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文件中。这怎么可能?

var url = window.location.pathname;
var folderpath = url.substring(0,url.lastIndexOf('/')+1);
alert(folderpath);
2个回答

这是不可能的,因为这会带来安全风险。人们为他们的文件夹结构使用相当真实的信息,访问文件夹名称本身会带来直接的风险。如此处所述:

使用javascript获取浏览器下载路径

大多数操作系统往往只是默认下载位置,这是用户通过他们使用的浏览器决定的。不是网站。

在 Chrome 中,可以在 chrome://settings/downloads 找到下载位置设置

你能分享@Leo我们是怎么做到的吗?
2021-03-23 11:26:22
您当然可以做的是告诉用户在浏览器中打开询问下载位置的可能性。
2021-03-29 11:26:22

这现在可以在大多数基于 Chromium 的桌面浏览器(以及即将推出的 safari)中使用文件系统访问 API 实现。https://caniuse.com/native-filesystem-api

可以在此处找到有关如何执行此操作的示例:https : //web.dev/file-system-access/#create-a-new-file

类似的东西:

async function getHandle() {
  // set some options, like the suggested file name and the file type.
  const options = {
    suggestedName: 'HelloWorld.txt',
    types: [
      {
        description: 'Text Files',
        accept: {
          'text/plain': ['.txt'],
        },
      },
    ],
  };

  // prompt the user for the location to save the file.
  const handle = await window.showSaveFilePicker(options);

  return handle
}

async function save(handle, text) {
  // creates a writable, used to write data to the file.
  const writable = await handle.createWritable();

  // write a string to the writable.
  await writable.write(text);

  // close the writable and save all changes to disk. this will prompt the user for write permission to the file, if it's the first time.
  await writable.close();
}

// calls the function to let the user pick a location.
const handle = getHandle();

// save data to this location as many times as you want. first time will ask the user for permission
save(handle, "hello");
save(handle, "Lorem ipsum...");

这将提示用户使用保存文件选择器,他可以在其中选择保存文件的位置。在选项中,您可以指定要保存的文件的建议名称和文件类型。

这将返回一个文件句柄,可用于将数据写入文件。执行此操作后,将要求用户对创建的文件具有写权限。如果获得批准,您的应用程序可以根据需要多次将数据保存到文件中,而无需重新提示用户,直到您应用程序的所有选项卡都关闭。

下次打开您的应用程序时,如果您再次使用相同的文件句柄(句柄可以保存在IndexedDB 中以在页面加载时保持它们),则会再次提示用户授予权限

文件系统访问 API 还允许您让用户选择现有文件,供您的应用程序稍后保存。https://web.dev/file-system-access/#ask-the-user-to-pick-a-file-to-read