Using Html5/Javascript to Generate and Save a File

Using HTML5/JavaScript to generate and save a file

OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:

1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).

2) Build the data URI:

uriContent = "data:application/octet-stream," + encodeURIComponent(content);

There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.

3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:

newWindow = window.open(uriContent, 'neuesDokument');

That's it.

Is it possible to write data to file using only JavaScript?

Some suggestions for this -

  1. If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
  2. If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
  3. To store some information on the client side that is considerably small, you can go for cookies.
  4. Using the HTML5 API for Local Storage.

It it possible to use javascript to save a file to same directory as current file?

Things have greatly changed with HTML5 and so the answer is "Yes!" provided that one is using a modern browser and/or one takes advantage of JavaScript libraries that may aid with this endeavor. Take a look here as well as here. If you alter your browser's download settings to the desired folder of your local web server, when you submit the form the file will be downloaded there. I tried this using google chrome 49 on a windows box using wampserver and the file was saved exactly in the specified folder. After forking the code here, it ran successfully on my local webserver from the directory where I wanted the new file to be downloaded.

The pertinent jQuery code from codepen.io:

$("#btn-save").click( function() {
var text = $("#textarea").val();
var filename = $("#input-fileName").val()
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename+".txt");
});

Javascript generate file and ask user to save it, possible?

Javascript: Create and save file The file known as FileSaver.js works fine :)

Cheers Robert Harvey

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());

saveByteArray([sampleBytes], 'example.txt');



JSFiddle: http://jsfiddle.net/VB59f/2

Is it possible to write html code using javascript (and save it)

The only way to have access to clients computer using JavaScript is NodeJS. With regular browser JavaScript, you cannot save files on the client's computer. If you want to stay with browser document.write or DOMElement.innerHTML = <div></div> are your options.

"Save As Video" but how to do it with javascript and html instead?

If your video is located on the same origin as your webpage (not your case)

<a href="/path/to/video.mp4" download="video">Download</a>

Rather simple, does not require Javascript, and works on every browser except IE.


If your video is from a different origin (your case)

When testing my solution, I found out that cross-origin downloads are blocked by Chrome and Firefox for security purposes.

a. If you control the server

If the server implements proprer CORS, or if you have control over the server and can add those CORS, you can use this script that I shamelessly took from this SO question :

<!-- The style="display:none;" is optional, you can remove it if you don't want the feature explained below. -->
<a id="download-link" href="javascript:alert('The video is not yet ready!')" download="video" style="display:none;">Download</a>
<script>

var a = document.getElementById("download-link");

function downloadResource(url, filename) {

// Current blob size limit is around 500MB for browsers
if (!filename) filename = url.split('\\').pop().split('/').pop();
fetch(url, {
headers: new Headers({
'Origin': location.origin
}),
mode: 'cors'
})
.then(response => response.blob())
.then(blob => {
let blobUrl = window.URL.createObjectURL(blob);

// Place the resource in the href of the link
a.href = blob;

// Bonus : Only show the link if and when the Javascript code has executed
a.style.display = "inline";
})
.catch(e => console.error(e));

}

downloadResource("https://invidious.fdn.fr/latest_version?id=NF_69Dyle1Y&raw&itag=22");

</script>

I added a little feature that will keep the link hidden until the file is completely downloaded. You can of course change this depending on your requirements.

b. If you don't control the server

If it uses CORS and allows all origins (or at least your origin), the script above should work.

If it doesn't, you're out of luck, sadly. You can still open the video in a new window and tell the user to right-click and "Save As" manually; it's less neat, but at least it works.

HTML5/JavaScript "Save As" Dialog for File Download

This is possible in desktop versions of latest Chrome-based browsers (Chrome, Edge, Opera).

Current support:
https://caniuse.com/mdn-api_window_showsavefilepicker

https://wicg.github.io/file-system-access/#api-showsavefilepicker


https://wicg.github.io/file-system-access/#enumdef-wellknowndirectory


We use this for working with PDF files: https://webpdf.pro/doc/ (draft for next release).

Note that you can suggest a file name and folder, customize the file type list, offer multiple types!
showSaveFilePicker
In fact, we have a method called exactly that: <pdf-file>.saveAs().

draft


Online version of Visual Studio Code is another recent user: https://vscode.dev/.


Apple and Firefox are likely to drag their feet on this one citing privacy/security concerns for at least the next few months though.



Related Topics



Leave a reply



Submit