5

js下载文件_字符串写入txt中并下载,或直接下载url链接文件

 2 years ago
source link: https://www.fly63.com/article/detial/11072
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
更新日期: 2022-01-26阅读量: 258标签: 文件分享

扫一扫分享

这篇文章主要介绍了js下载txt文件的方式,包含2种:一是将字符串写入到txt文件中并下载,二是直接下载url链接文件。

一、字符串写入到txt文件中再下载

代码实现:

function downloadByBlob (fileName, content) {
let blob = new Blob([content], {
type: "text/plain;charset=utf-8"
});
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function(e) {
let a = document.createElement('a');
a.download = fileName;
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
let txt='https://www.fly63.com'
downloadByBlob("data.txt",txt) //文件名data.txt

当然这里不局限于txt后缀的文件,凡是文本类型的,比如.svg,.html等等都可以这样使用,只需要修改上面的文件后缀即可。

二、直接下载url链接文件

js不打开直接下载txt文件。

1.调用 downloadUrlFile(url); //url=文件来源。地址//获取文件blob数据并保存
2.saveAs(xhr.response, fileName);开始下载

代码实现:

/**
* 获取页面文件名
* @param url 文件url
*/
function downloadUrlFile(url) {
url = url.replace(/\\/g, '/');
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
//xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
xhr.onload = () => {
if (xhr.status === 200) {
// 获取文件blob数据并保存
var fileName = getFileName(url);
saveAs(xhr.response, fileName);
}
};

xhr.send();
}
/**
* URL方式保存文件到本地
* @param data 文件的blob数据
* @param name 文件名
*/
function saveAs(data, name) {
var urlObject = window.URL || window.webkitURL || window;
var export_blob = new Blob([data]);
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
save_link.href = urlObject.createObjectURL(export_blob);
save_link.download = name;
save_link.click();
}
/**
* 根据文件url获取文件名
* @param url 文件url
*/
function getFileName(url) {
var num = url.lastIndexOf('/') + 1
var fileName = url.substring(num)
//把参数和文件名分割开
fileName = decodeURI(fileName.split("?")[0]);
return fileName;
}
let url="https://www.fly63.com/test.txt"
downloadUrlFile(url)//调用

当然除了txt文件,我们同样可以使用上述方法下载其他类型的文件,比如ppt,doc,xls等。

站长推荐

1.云服务推荐: 国内主流云服务商/虚拟空间,各类云产品的最新活动,优惠券领取。领取地址:阿里云腾讯云硅云

链接: https://www.fly63.com/article/detial/11072


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK