简体   繁体   English

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

[英]Download A File At Different Location Using HTML5

I am downloading files using HTML5 from below codes that you can see live in action at JSBIN HTML5 Download File DEMO and its working perfectly file and downloading my files at my browser default Download Folder .我正在从下面的代码中使用 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>

But I want to download it on different location.但我想在不同的位置下载它。 Like I am using this code offline and just have the upper code in my index.html file.就像我离线使用此代码一样,我的index.html文件中只有上层代码。 When I run this file in my browser from file:///C:/Users/Public/Desktop/ then it download the file and save it at file:///C:/Users/Public/Downloads/ .当我在浏览器中从file:///C:/Users/Public/Desktop/运行此文件时,它会下载该文件并将其保存在file:///C:/Users/Public/Downloads/ So I want to download this file from where its called.所以我想从它调用的地方下载这个文件。 For this I am picking the path from the following code.为此,我从以下代码中选择路径。 and its giving me the path as /C:/Users/Public/Desktop/ so I want to save file here.它给我的路径为/C:/Users/Public/Desktop/所以我想在这里保存文件。 Whereever my this index.html file will go, it will download the file and save it along index.html file.无论我的这个index.html文件去哪里,它都会下载该文件并将其保存在index.html文件中。 How is this possible?这怎么可能?

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

It's not possible because this poses a security risk.这是不可能的,因为这会带来安全风险。 People use fairly real information for their folder structure and accessing the folder names in itself poses an immediate risk.人们为他们的文件夹结构使用相当真实的信息,访问文件夹名称本身会带来直接的风险。 As described here:如此处所述:

Get browser download path with javascript 使用javascript获取浏览器下载路径

Most OSs tend to just default to a Download location and this is something the user decides through the Browser they use.大多数操作系统往往只是默认下载位置,这是用户通过他们使用的浏览器决定的。 Not the website.不是网站。

In Chrome, Download location setting can be found at chrome://settings/downloads在 Chrome 中,可以在 chrome://settings/downloads 找到下载位置设置

This is now possible in most Chromium based desktop browsers (and safari soon), using the File System Access API.这现在可以在大多数基于 Chromium 的桌面浏览器(以及即将推出的 safari)中使用文件系统访问 API 实现。 https://caniuse.com/native-filesystem-api https://caniuse.com/native-filesystem-api

An example on how to do this can be found here: https://web.dev/file-system-access/#create-a-new-file可以在此处找到有关如何执行此操作的示例: https : //web.dev/file-system-access/#create-a-new-file

Something along the lines of:类似的东西:

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...");

This will prompt the user with a save file picker where he can choose a location to save the file to.这将提示用户使用保存文件选择器,他可以在其中选择保存文件的位置。 In the options, you can specify a suggested name and the file type of the file to be saved.在选项中,您可以指定要保存的文件的建议名称和文件类型。

This will return a file handle, which can be used to write data to the file.这将返回一个文件句柄,可用于将数据写入文件。 Once you do this, the user is asked for write permission to the created file.执行此操作后,将要求用户对创建的文件具有写权限。 If granted, your app can save data to the file as many times as you like, without re-prompting the user, until all tabs of your app are closed.如果获得批准,您的应用程序可以根据需要多次将数据保存到文件中,而无需重新提示用户,直到您应用程序的所有选项卡都关闭。

The next time your app is opened, the user is prompted for permission again, if you use the same file handle again (the handles can be saved in IndexedDB to persist them across page loads).下次打开您的应用程序时,如果您再次使用相同的文件句柄(句柄可以保存在IndexedDB 中以在页面加载时保持它们),则会再次提示用户授予权限。

The File System Access API also allows you to let the user pick an existing file, for your app to save later.文件系统访问 API 还允许您让用户选择现有文件,供您的应用程序稍后保存。 https://web.dev/file-system-access/#ask-the-user-to-pick-a-file-to-read 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