簡體   English   中英

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

[英]Download A File At Different Location Using HTML5

我正在從下面的代碼中使用 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);

這是不可能的,因為這會帶來安全風險。 人們為他們的文件夾結構使用相當真實的信息,訪問文件夾名稱本身會帶來直接的風險。 如此處所述:

使用javascript獲取瀏覽器下載路徑

大多數操作系統往往只是默認下載位置,這是用戶通過他們使用的瀏覽器決定的。 不是網站。

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

這現在可以在大多數基於 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM