首页 > 解决方案 > 如何在 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();
}
            

标签: javascriptfilemoduleblobwrite

解决方案


推荐阅读