11

Sometimes in the front-end development process, you may encounter such a demand scenario: you need to download the text content on the page to a file, the content may be a large text field, such as a blog post, or it may be returned by the back-end interface JSON data.

1. Download the text

So how do you need to implement JS to download text content? It can be achieved with the help of the Blob object and the download attribute of the a tag . The specific code is as follows:

Blob object represents an immutable, raw data file-like object. Its data can be read in text or binary format, or converted to ReadableStream for data manipulation;

a The download attribute of the tag is newly added in HTML5, which is used to directly download files;

 function downloadText(fileName, text) {
    const url = window.URL || window.webkitURL || window;
    const blob = new Blob([text]);
    const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    saveLink.href = url.createObjectURL(blob);
    // 设置 download 属性
    saveLink.download = fileName;
    saveLink.click();
}

Let's test it, you can test it directly in Chrome's console

 downloadText('test.txt', '测试')

After running, you can see that the browser will download a file named test.txt

2. Download JSON

Sometimes the back-end interface returns a JSON object. In order to facilitate viewing and checking of data, you may want to download it to a file, so you only need to modify the method of downloading text slightly. The specific code is as follows:

 function downloadJson(fileName, json) {
    const jsonStr = (json instanceof Object) ? JSON.stringify(json) : json;
    
    const url = window.URL || window.webkitURL || window;
    const blob = new Blob([jsonStr]);
    const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    saveLink.href = url.createObjectURL(blob);
    saveLink.download = fileName;
    saveLink.click();
}

Let's test it

 downloadJson('test.json', {id: 1, name: 'js'})

After running, the browser will automatically download a file named test.json with the following contents:

 {"id":1,"name":"js"}

3. Download JSON and format

Sometimes you may want the json data saved to the file to be formatted, so that it is easy to view, then you only need to adjust the JSON.stringify() method a little bit. Let's take a look at the definition of the JSON.stringify() method first.

 JSON.stringify(value[, replacer [, space]])

value

  • The value to be serialized into a JSON string.

replacer optional

  • If the parameter is a function, during the serialization process, each property of the serialized value will be converted and processed by the function; if the parameter is an array, only the property names contained in the array will be Will be serialized into the final JSON string; if this parameter is null or not provided, all properties of the object will be serialized.

space optional

  • Specifies a whitespace string for indentation, used for pretty-printing; if the parameter is a number, it represents how many whitespaces there are; the upper limit is 10. If the value is less than 1, it means there is no space; if the parameter is a string (when the length of the string exceeds 10 letters, take the first 10 letters), the string will be treated as a space; if the parameter is not provided ( or null), there will be no spaces.

If you want to format JSON, you can pass in a space parameter, as follows:

 JSON.stringify(json, null, 4);

In addition to using 4 spaces, you can also indent with a tab character (\t), as follows:

 JSON.stringify(json, null, '\t');

The download and format JSON method is modified as follows:

 function downloadJson(fileName, json) {
    const jsonStr = (json instanceof Object) ? JSON.stringify(json, null, 4) : json;
    
    const url = window.URL || window.webkitURL || window;
    const blob = new Blob([jsonStr]);
    const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    saveLink.href = url.createObjectURL(blob);
    saveLink.download = fileName;
    saveLink.click();
}

Let's test it

 downloadJson('test.json', {id: 1, name: 'js'})

After running, the browser will automatically download a file named test.json with the following contents:

 {
    "id": 1,
    "name": "js"
}

十方
226 声望433 粉丝