Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to download the json file according to the url returned by the backend

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to download json files according to the url returned from the backend". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "how to download json files according to the url returned from the backend" can help you solve the problem.

Requirement scenario description

Sometimes the asynchronous interface will return a url address, and then the front end needs to download the file resources according to this url address. The url is actually a static resource address, not an interface address that is processed internally by the back-end interface. So when you try to use the a tag to execute the url address as follows, you will find that it is a direct preview of an open json file (or a txt,js file, etc.)

Download json

If you open the url directly in the browser window, you will find that it also opens the json file directly. The addresses of accessible static resources such as txt,js,css are also opened directly (this may be called a preview, in two forms, one is to preview the file, the other is to download the file) instead of downloading. This is related to the way the resource address is returned (responseType), which may be returned by default in the form of a byte stream or character stream, which can be previewed by the browser, so it is opened directly (the preview file mode is executed). We may be more common is the picture, it can directly open the preview in the browser, this is also because it returns the form of base64 image, it can be recognized by the browser, so the browser will normally execute the file preview mode, rather than download mode.

For example, static resources in the same location, one is json and the other is .zip zip file. With two url, you will find that the url of the json file is executed in the browser window, and the browser executes the preview mode, opening the file directly. Enter the url of the compressed .zip file in the browser window, and instead of performing the preview mode, the browser executes the download mode and downloads the file directly.

The following is a schematic diagram of two tests

So what if you want to download directly instead of previewing based on the url returned by this interface (a static resource address, such as the resource address of a json or txt file)?

Processing scheme keywords: asynchronous download, set responseType = 'blob'.

Analysis of realization ideas

1. Set the return mode of the request to responseType = 'blob',. If it is not set, it may not be able to open normally after download.

two。 Set the request address, request method, and necessary request header parameters, such as token, etc., which can be set as needed.

3. Converts the returned byte stream (character stream) to a blob object

Const blob = new Blob ([res.data]) / / convert a byte stream (character stream) to a blob object

4. Create a resource url for the blob

Let url = window.URL.createObjectURL (blob)

5. Use the url to create an a tag to simulate the click event to perform the download

This step is consistent with the way we usually download resource files synchronously. After downloading, be careful to release the ObjectURL of the blob object.

Let link = document.createElement ('a') link.style.display = 'none'link.href = urllink.download = filenamedocument.body.appendChild (link) link.click () document.body.removeChild (link) / / download completed removing element window.URL.revokeObjectURL (url) / / release the blob object

Tips:ie does not support downloading blob resources directly, and you can use window.navigator.msSaveOrOpenBlob (blob, filename) to solve this problem.

/ / solving the problem that ie does not support downloading blob resource if ('msSaveOrOpenBlob' in navigator) {window.navigator.msSaveOrOpenBlob (blob, filename) return}

The above code execution in ie will automatically open a query window, which will ask you if you want to download or preview, select download and you can download normally.

The following is a screenshot of downloading blob in ie

Complete demo example xhr asynchronously downloads resource files such as json, axios asynchronously downloads resource files such as json, import axios from 'axios'export default {name:' DownloadFile', methods: {axiosDownload () {/ / config is a configuration object and can be set on demand, for example, setting const config = {} / / in responseType,headers, such as token, may be critical, especially when downloading But when you download it and open the exception. Config.responseType = 'blob' axios.get (' http://localhost:8278/package.json', config). Then (res = > {const blob = new Blob ([res.data]) / / convert a byte stream (character stream) to a blob object this.blobDownload (blob)})} / * download file: download the file in the form of blob object * @ param blob * @ param filename * / blobDownload (blob, filename = 'file .json') {let url = window.URL.createObjectURL (blob) / / solve the problem that ie does not support downloading blob resource if ('msSaveOrOpenBlob' in navigator) {window.navigator.msSaveOrOpenBlob (blob) Filename) return} let link = document.createElement ('a') link.style.display = 'none' link.href = url link.download = filename document.body.appendChild (link) link.click () document.body.removeChild (link) / / download completed removing element window.URL.revokeObjectURL (url) / / release blob object} Header parameters such as xhrDownload (params) {/ / token and request method can be configured as needed const token = localStorage.getItem ('token') | |' const url = 'http://localhost:8278/package.json' let xhr = new XMLHttpRequest () / / get xhr.open (' get', url +'? timeStamp=' + new Date (). GetTime (), true) xhr.setRequestHeader ('Cache-Control') 'no-cache') xhr.setRequestHeader (' Content-type', 'application/json') / / xhr.setRequestHeader (' kms-token', token) / / return type blob If you do not set it, you will not be able to open excel xhr.responseType = 'blob' / / define the processing function for request completion. You can also add the load box / disable download button logic xhr.onload = function () {/ / request completion if (this.status = 200) {let blob = this.response let url = window.URL.createObjectURL (blob) / / generate url before the request. Create an a tag to download let a = document.createElement ('a') a.download = 'income and expenditure list .json' a.href = url a.click ()}} xhr.send (JSON.stringify (params))} about "how to download json files based on the url returned from the backend". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report