zoukankan      html  css  js  c++  java
  • js操作一般文件和csv文件

    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("文件内容如下
      "+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);
      }    
      
  • 相关阅读:
    Day Six(Beta)
    Day Five (beta)
    Day Four(Beta)
    Day Three(Beta)
    Day Two(Beta)
    Day One(Beta)
    项目冲刺——总结
    beta版本贡献率
    软件工程实践总结
    团队作业--Beta版本冲刺
  • 原文地址:https://www.cnblogs.com/ye-hcj/p/10353974.html
Copyright © 2011-2022 走看看