js操作一般文件和csv文件

  1. 将文本文件读成字符串

    <input type="file" >
    
    document.getElementById("upload").addEventListener("change", function() {
        var files = this.files;
        if(files.length == 0) {
            console.log("没有文件");
            return;
        }
    
        var reader = new FileReader();
    
        reader.readAsText(files[0]);
        reader.onload = function(e) {
            console.log("文件内容如下\n"+e.target.result);
        }
    })
    
  2. 将读取的图片展示在页面上

    <input type="file" >
    
    document.getElementById("upload").addEventListener("change", function() {
        var files = this.files;
        if(files.length == 0) {
            console.log("没有文件");
            return;
        }
    
        var reader = new FileReader();
    
        reader.readAsDataURL(files[0]);
        reader.onload = function(e) {
            var img = new Image();
            img.style.width = "200px";
            img.style.height = "100px"
            img.onload = function() {
                document.body.appendChild(img);
            }
            img.src = e.target.result;
        }
    })
    
  3. 处理和下载csv文件

    var blob = new Blob([
        `Year,Make,Model,Description,Price
        1997,Ford,E350,"ac, abs, moon",3000.00
        1999,Chevy,"Venture ""Extended Edition""","",4900.00
        1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
        1996,Jeep,Grand Cherokee,"MUST SELL!
        air, moon roof, loaded",4799.00`
    ])        
    
    if(window.navigator.msSaveOrOpenBlob){
        window.navigator.msSaveBlob(blob, "test.csv");
    }else {
        var a = window.document.createElement("a");
        a.href = window.URL.createObjectURL(blob, {
            type: "text/plain"
        });
        a.download = "test.csv";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }    
    

相关文章:

  • 2022-12-23
  • 2021-11-23
  • 2021-11-23
  • 2021-12-26
  • 2021-04-09
  • 2021-08-28
猜你喜欢
  • 2022-01-22
  • 2021-12-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-17
相关资源
相似解决方案