码迷,mamicode.com
首页 > Web开发 > 详细

js操作一般文件和csv文件

时间:2019-02-06 19:54:45      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:fileread   png   esc   nload   log   files   tor   child   move   

js操作一般文件和csv文件

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

    <input type="file" id="upload">
    
    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" id="upload" accept="image/png">
    
    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);
    }    

js操作一般文件和csv文件

标签:fileread   png   esc   nload   log   files   tor   child   move   

原文地址:https://www.cnblogs.com/ye-hcj/p/10353974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!