【问题标题】:Download A File At Different Location Using HTML5使用 HTML5 在不同位置下载文件
【发布时间】:2016-04-24 13:37:14
【问题描述】:

我正在使用 HTML5 从下面的代码下载文件,您可以在 JSBIN HTML5 Download File 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 文件一起保存。这怎么可能?

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

【问题讨论】:

  • 不可能,默认下载位置是各大操作系统的下载目录,用户可以更改,不是你。
  • 好的,这样是否可以在下载文件时获取用户在 JavaScript 变量中的 Default DownLoad Folder 的目录路径?
  • 你也不能得到。 stackoverflow.com/a/9840961/2151050
  • 谢谢,请在回答中添加两个 cmets 和描述,以便我可以完美选择它,其他人可以得到帮助。

标签: javascript html download


【解决方案1】:

现在,大多数基于 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

【讨论】:

    【解决方案2】:

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

    Get browser download path with javascript

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

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

    【讨论】:

    • 你可以做的当然是告诉用户在浏览器中打开询问下载位置的可能性。
    • 您能分享一下@Leo 我们如何做到这一点吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多