简体   繁体   中英

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 .

<!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. 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/ . 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. Whereever my this index.html file will go, it will download the file and save it along index.html file. 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

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

This is now possible in most Chromium based desktop browsers (and safari soon), using the File System Access 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

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

The File System Access API also allows you to let the user pick an existing file, for your app to save later. https://web.dev/file-system-access/#ask-the-user-to-pick-a-file-to-read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM