How to save a file with JavaScript


JavaScript is one of the most popular programming languages ​​out there mainly because it handles the front end of websites while running within a browser. With advances in web standards, we are using it more and more to do more and more tasks that were previously very difficult or impossible to do with just JavaScript.

In this tutorial you will learn how to create and save files with JavaScript. We will discuss three different techniques you can use to do this.

Using data URLs to save files

The simplest way to save a file is to use data URLs that include all relevant information. These data URLs are special URLs that are preceded by data: scheme. They are ideal for embedding small files in your HTML documents. These URLs follow the following syntax:

The mediatype token is actually a MIME type that specifies the nature and format of a document or file. Its default is text/plain;charset=US-ASCII. The base64 the token is optional and needed only when you want to store binary data in a textual way. We specify our actual data after all of these tokens.

We can use the download attribute to specify the name of the file where we want to put all our content after download. Here is an example of using all of these attributes together:

JavaScript can be very useful when you want to make everything dynamic. Here is an example:

Let’s start by selecting our link using the querySelector() method and then create a group of variables to store the file name and its contents. Using pattern literals allows us to easily work with multiline strings.

We create our data URL by concatenating the metadata with the actual content encoded using the encodeURIComponent() function. The following CodePen demo demonstrates this method of saving text files using JavaScript.

Using blobs to create and save files

Blobs are file-like objects in JavaScript that contain raw data. This raw data can be read as text or as binary data. In this tutorial we will use blobs to create and save files in JavaScript.

We can create our blobs using the Blob() constructor that accepts an array of specific objects to insert into the blob. You can pass the MIME type of the data as a key-value pair in an object which is the second parameter of Blob() builder. It is an empty string by default.

We could modify the last example in our previous section to use BLOBs with the following JavaScript code:

We create ours textBlob calling the Blob() builder and passing ours text variable to it as an array element. After that, let’s just set the value of href And download attributes. The URL in this case is created by calling the createObjectURL() function that returns a string that contains the URL of the object we passed to it.

Let’s go a step further and create a blob where the text is dynamically obtained from a textarea element on the web page. You will be able to write anything you like in the textarea and then click Save the file button to save it as a file.

Let’s start by getting a reference to our button and then hearing its click events. Once the button is clicked, we get the value of ours textarea element and convert it to a blob. Next, we create a URL that references our blob and assign it to href attribute of the anchor tag we created.

You can try it in the following CodePen demo. As an exercise, try modifying the code so that it saves the file with a name entered by users instead of something static.

How to save the file in a specific folder using JavaScript?

Let’s start by getting this question out of our way first. In short, it is not possible to arbitrarily choose the directory in which a file is saved in JavaScript. Only the user has control over where a file is saved.

The reason a web developer can’t have complete control over where a file is saved by the browser has to do with security. The internet would be much less secure if every website had access to the filesystem on your device. They could simply inject malicious code into your system or display private information.

Previously, it was not possible to save a file anywhere except to the default download folder which was dictated by browser settings and not individual websites. However, the File System Access API allows developers to suggest where to save a file after they have been granted access by the user. Note that broader browser support currently lacks the API, and browsers that support it do so only partially.

Let’s modify our last example from the previous section to create and save a file in JavaScript with the File System Access API.

As usual, let’s start by creating a blob of text inside the textarea element. Let’s create an object that contains several options for our file selector that appears when we call the showFilePicker() method. We can suggest a name to save the file here and also pass a number of file types allowed to save. This method returns a FileSystemFileHandle on which we can call the createWritable() method.

The createWritable() the method creates a writable stream and we write the blob we created earlier in this stream. Finally, we close our writable stream. At this point, the contents of the stream are saved in the file.

Try writing something in the textarea of the following CodePen, and then click Save the file button. The demo won’t work in Firefox, so you should try using Chrome or Edge.

Final thoughts

In this tutorial, we learned three different techniques for creating and saving files in JavaScript. The first two techniques require us to create anchor tags and assign values ​​to them href And download attributes. The latest technique involves using the File System Access API and gives us better control over different aspects of the process such as changing the default download location with user permission. However, it does not currently have significant browser support for use in real projects.



Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *