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

Muh*_*san 1 html javascript html5 download

我正在使用HTML5从以下代码下载文件,您可以在JSBIN HTML5下载文件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>
Run Code Online (Sandbox Code Playgroud)

但我想在不同的位置下载它.就像我离线使用这个代码一样,我的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);
Run Code Online (Sandbox Code Playgroud)

Dan*_*ndy 16

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

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

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

  • 您可以做的当然是告诉用户打开浏览器中询问下载位置的可能性。 (2认同)

swi*_*ynx 11

现在,大多数基于 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...");
Run Code Online (Sandbox Code Playgroud)

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

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

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

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