Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html/JavaScript: Overwrite file every time it downloads

Is it possible to overwrite a file each time it saves. I have a textarea in html and i'm using JavaScript to save the text to a file. It is currently saving as: test.txt, test(1).txt, test(2).txt. Is it possible to get it to save a test.txt every time it's downloaded.

The code i'm using to download is the following:

function saveTextAsFile()
{      
    var textToWrite = document.getElementById("inputTextToSave").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'plan/text'});
    var fileNameToSaveAs = "test.txt";
    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "My Hidden Link";
    window.URL = window.URL || window.webkitURL;
    downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}

Thanks for your help.

like image 418
Niall_Maher Avatar asked Oct 18 '25 13:10

Niall_Maher


1 Answers

No , a javascript script doesn't have access to the filesystem and therefore cant manipulate files, all it can do is suggest to the browser that a stream wants to be downloaded and also suggest a name for that stream. The browser is responsible for deciding what and how will be downloaded (you can add plugins and extensions to the browsers to enforce this particular behavior, but i do not think that this was what you needed)

EDIT: On second note you could actually do that with a java applet. However i cannot help you with that, and in all sincerity, you should not (for one it wont work on chrome, also unless you have a really important reason to, it would be like killing a mosquito with a nuclear bomb, not to mention the chance of accidentally deleting a file from the user's side and a storm of alerts that would make your application look suspicious as it wont have any real reason to use java from they eyes of the user)

like image 58
Elentriel Avatar answered Oct 21 '25 03:10

Elentriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!