js实现下载(文件流、文件链接)
时间: 2024-01-27 14:05:51 浏览: 82
JS可以使用`XMLHttpRequest`对象来实现文件下载。以下是两种方式:
1. 下载文件流
```javascript
function downloadFile(data, fileName) {
let blob = new Blob([data]);
if (window.navigator.msSaveOrOpenBlob) {
// IE10+
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
let link = document.createElement("a");
if (link.download !== undefined) {
let url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
```
使用方式:
```javascript
let data = '这是文件流的数据';
let fileName = 'file.txt';
downloadFile(data, fileName);
```
2. 下载文件链接
```javascript
function downloadFile(url, fileName) {
let link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
```
使用方式:
```javascript
let url = 'http://www.example.com/file.txt';
let fileName = 'file.txt';
downloadFile(url, fileName);
```
阅读全文