1. Use JavaScript to download browser files:
function downloadFile(url, filename) {
// 创建一个隐藏的<a>标签
var a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename;
// 将<a>标签添加到页面中
document.body.appendChild(a);
// 触发<a>标签的点击事件,开始下载文件
a.click();
// 移除<a>标签
document.body.removeChild(a);
}
// 使用示例
downloadFile('http://www.baidu.com/file.txt', 'my.txt');
(1) A function is defined that accepts two parameters: the URL of the file and the file name to be saved.
(2) This function creates a hidden <a>
tag, sets the file's URL and file name as its properties, and then adds it to the page. Finally, <a>
the click event of the tag is triggered, and the browser automatically downloads the file.
(3) After the download is completed, we <a>
remove the tag from the page.
2. Directly through the href attribute of the a tag: (get request)
<a href='www.baidu.com?id=12' download="name.txt">下载</a>
3. Download file stream (post request)
axios({
url:'www.baidu.com/downloadBillFreezeInfo?id=' + id,
method:'post'
responseType: 'blob',})
.then((response) => {
const url = window.URL.createobjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download',fileName);
document.body.appendchild(link);
link.click();
document.body.removechild(link);
})
responseType
Is a configuration option in Axios that is used to specify the data type of the server response. It can be set to the following types:
arraybuffer
: Returns an object containing binary dataArrayBuffer
.blob
: Returns an object containing binary dataBlob
.document
: Returns an HTML document object.json
: Returns a JavaScript object that is parsed from the JSON data returned by the server.text
: Returns a string that is the text data returned from the server.
The default responseType
setting is json
that Axios will automatically parse the JSON data returned by the server into JavaScript objects.
If you need to get other types of data, you can responseType
do it through settings.
For example, if you need to download a binary file, set it responseType
to arraybuffer
or blob
.