javascript - 如何在 Javascript 上使用 Blob 编写和下载文件
问题描述
所以,我有一个编码挑战要在 Javascript 中解决,但到目前为止我还没有找到答案。这是交易:
将 1 到 99 的数字(每个数字都可以被 5 整除)写入文件。(另外到这个文件中,不要在正常输出中输出可被 5 整除的数字,文件中的值是换行符分隔的)
您应该可以下载此文件。
我知道这个练习的写法很奇怪,但我没有写。所以这是我的解释:
function download() {
let outputNum = [];
for (let i = 1; i <= 99; i++) {
outputNum.push(i);
}
//If condition to generate numbers dividible by
if (outputNum % 5 == 0) {
document.write(outputNum);
}
function result(N) {
// iterate from 0 to N
for (let num = 0; num < N; num++) {
// Short-circuit operator is used
if (num % 5 == 0)
document.write(num + " ");
}
}
let N = 100;
result(N);
let blabla = result();
//create a blob
const blob = new Blob([outputNum], {type: "text/plain"});
downloadFile(blob, "Ilovepotato.txt");
}
//Function to generate a download with blob and file name.
function downloadFile(blob, filename){
/*Create a URL for the Blob.
URL.createObjectURL() erzeugt einen DOMString,
welcher eine URL enthält, die das übergebene Objekt repräsentiert.*/
const url = window.URL.createObjectURL(blob);
//Anchor Tag to download
const a = document.createElement("a");
//Before click we need to add some prop to "a" tag.
a.href= url;
a.download = filename;
// Click Event
a.click();
}
解决方案
推荐阅读
- java - Spring、Hibernate 和 JSF 的集成
- c# - func 上的 C# 可选参数丢失泛型类型推断
- .net - 使用 mscoree.CorRuntimeHost 在 VB6 中托管 .Net 会导致“需要对象”错误
- javascript - JavaScript .CSV 转数组
- c# - FPS 播放器 Look.At() 对象
- python - 带有附加参数的自定义聚合原语?
- scala - Apache Toree Spark 内核无法启动 (java.lang.NoSuchMethodError)
- javascript - 如何在 javascript 中使用原型模式?
- javascript - 视差定位问题 Bootstrap 4
- autofac - AutoFake 指定的对象未被识别为假对象。尝试存根 sut 的方法时出现问题