Как сохранить файл в javascript
Перейти к содержимому

Как сохранить файл в javascript

  • автор:

Создание и сохранение файла JavaScript

В этом руководстве рассказывается, как создать и сохранить файл в JavaScript.

Создавать файлы и хранить их на стороне сервера NodeJS легко, но на стороне клиента есть несколько вариантов. В этом руководстве мы пишем настраиваемую функцию, которая помогает нам создавать файлы с использованием данных, а затем сохранять их. В современных браузерах у нас есть функция под названием msSaveOrOpenBlob, которая помогает нам сохранять файл. Но в старых браузерах мы сначала генерируем ссылку на файл, а затем загружаем его, добавляя атрибут download к тегу привязки.

В приведенной выше функции мы проверяем, поддерживает ли браузер msSaveOrOpenBlob , и, если он найден, мы используем его для сохранения файла. В противном случае мы создаем тег привязки, указывающий на созданный файл. Мы добавляем атрибут загрузки к тегу привязки и прикрепляем этот тег к телу документа. Мы используем JavaScript, чтобы щелкнуть по нему, что запускает загрузку, и таким образом мы сохраняем файл. Затем мы удаляем этот тег привязки из тела и отменяем созданный URL.

How to Save a File With JavaScript

Monty Shokeen

Monty Shokeen Last updated Jun 19, 2022

JavaScript is one of the most popular programming languages around, primarily because it handles the front-end of websites while running inside a browser. With the advancements in web standards, we have been using it to accomplish more and more tasks that were earlier either 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 that you can use to do so.

Using Data URLs to Save Files

The easiest way to save a file is to use Data URLs that include all the relevant information. These data URLs are special URLs that are prefixed with the 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 value is text/plain;charset=US-ASCII . The base64 token is optional and is needed only when you want to store binary data textually. We specify our actual data after all 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 these attributes together:

JavaScript can be very handy when you want to make the whole thing dynamic. Here is an example:

We begin by selecting our link using the querySelector() method and then create a bunch of variables to store the file name and its contents. Using template literals allows us to work with multi-line strings easily.

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

Using Blobs to Create and Save Files

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

We can create our own blobs using the Blob() constructor, which accepts an array of specific objects to be put inside the blob. You can pass the MIME type of the data as key-value pair in an object that is the second parameter of the Blob() constructor. 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 our textBlob by calling the Blob() constructor and passing our text variable to it as an array element. After that, we simply set the value of the href and download attributes. The URL in this case is created by calling the createObjectURL() function, which returns a string that contains the URL for the object that we passed to it.

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

We begin by getting a reference to our button and then listening to its click events. Once the button is clicked, we get the value of our textarea element and convert it to a blob. After that, we create a URL that references our blob and assign it to the href attribute of the anchor tag that we created.

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

How to Save File in a Specific Folder Using JavaScript

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

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

Earlier, it wasn’t possible to save a file anywhere except the default download folder, which was dictated by the browser’s setting and not individual websites. However, the File System Access API allows developers to suggest where a file can be saved after they have been granted access by the user. Keep in mind that wider browser support is currently lacking for the API, and the browsers which do support it only do so 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, we begin by creating a blob of the text inside the textarea element. We create an object that contains different options for our file picker that shows up when we call the showFilePicker() method. We can suggest a name to save the file here and also pass an array of allowed file types to save. This method returns a FileSystemFileHandle on which we can call the createWritable() method.

The createWritable() method creates a writable stream, and we write the blob we created earlier to this stream. Finally, we close our writable stream. At this point, the content from the stream is saved to the file.

Try writing something in the textarea of the following CodePen, and then click on the Save File button. The demo will not work in Firefox, so you should try using Chrome or Edge.

Final Thoughts

In this tutorial, we learned three different techniques of creating and saving files in JavaScript. The first two techniques require us to create anchor tags and assign values to their href and download attributes. The last technique involves using the File System Access API and gives us better control over different aspects of the process like changing the default download location with the user’s permission. However, it doesn’t currently have significant browser support to be used in real projects.

5 Ways To Create & Save Files In Javascript (Simple Examples)

Welcome to a tutorial on how to create and save files in Javascript. Well, this will be kind of a complicated process for beginners. To keep things simple – Saving files on the server-side NodeJS is a breeze, but it is tricky to directly save files on the client side because of security restrictions. That said, there are many methods we can use.

  1. Use a library called FileSaver – saveAs(new File([«CONTENT»], «demo.txt», ));
  2. Create a blob object and offer a “save as”.
    • var a = document.createElement(«a»);
    • a.href = window.URL.createObjectURL(new Blob([«CONTENT»], ));
    • a.download = «demo.txt»;
    • a.click();
  3. Upload the data, save it on the server.
    • var data = new FormData();
    • data.append(«upfile», new Blob([«CONTENT»], ));
    • fetch(«SERVER.SCRIPT», < method: "POST", body: data >);
  4. Create a writable file stream.
    • const fileHandle = await window.showSaveFilePicker();
    • const fileStream = await fileHandle.createWritable();
    • await fileStream.write(new Blob([«CONTENT»], ));
    • await fileStream.close();
  5. In NodeJS, simply use the file system module – require(«fs»).writeFile(«demo.txt», «Foo bar!»);

That covers the basics, but let us walk through detailed examples in this tutorial – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

How to Save Files in JavaScript

Save As

In the web world, saving a file or “Save As” means downloading a file to the client’s machine. There isn’t a built-in method in JavaScript that allows us to do so. What we typically do (if we have a static file link) is add an anchor element in HTML and use the download attribute to make it downloadable. Something like this:

The problem is that we don’t always want the user to download when clicking on a link because we could have a bunch of logic before downloading or some dynamic data created without a static link. Let’s go through a few simple steps to create a saveAs function for downloading one or multiple files in JavaScript!

Generate a file:

Unless we have static files available publicly on the server, we need to create content using a Blob , a file-like object in JavaScript.

Let’s create a function that will take some data as a parameter and return a new Blob text:

Of course, a Blob object has a lot more than just a plain text type. You can learn more in the official documentation.

Create a saveAs function:

Let’s look at two approaches for saving/downloading a file in JavaScript:

1. Use an Anchor element <a>

We can dynamically create an anchor element in JavaScript using createElement and then programmatically invoke the click event. Here is a basic example:

But to download a file, we need to pass it download and href attributes. The download will hold the file name and extension and the href will require a URL. Let’s create a function and put all the implementation together:

If we are using a static file with a relative path, all we need to do is this:

Download only works for same-origin URLs. Meaning, href can’t be a path different than your websites’ otherwise the behavior will change and it will redirect instead of downloading.

If the content is generated dynamically, we’ll need to create a blob and convert it to an object URL to make it downloadable. Also, we need to release the object at the very end when no longer needed:

Let’s improve the function to make it re-usable and have it support both options:

2. Use file-saver library

FileSaver.js is a great solution to saving files on the client-side without having to write our own custom code.

First, we need to install the library:

Then, use it as follows:

Zip and download multiple files

In certain cases, we need to download multiple files in one hit. Although this can be achieved by looping through the files and triggering the saveAs function, the user experience isn’t great and we’ll end up with so many files added to the download folder.

An alternative solution is to use JSZip, a library for creating, reading, and editing .zip files.

First, we need to install the library:

Then, we’ll create an async function that does the following logic:

  1. Generates multiple files using createBlog function we did earlier:
  1. Instantiate the JSZip and add the files
  1. Generate the zip folder and as soon as it’s ready, we can call the saveAs function we did earlier:

Here is the full function:

I hope you enjoyed learning from this article and if you have any questions, please leave a comment below.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *