html5 converts the absolute path into a picture file object

EDITORIAL: copy and paste purely based on someone's blog Great God, because of work need to use this, it copied the way shameless plagiarism, in fact, just want to record it, so that the future can be used.
Original: https://blog.csdn.net/weixin_33957648/article/details/86251969

Basic knowledge
1. Understanding FileList objects and file objects in HTML5.

In HTML5, FileList object represents the list of files selected by the user. By adding multipe property within the file control allows you to select multiple files at once. Each file selected by the user in control is a
file object, and the object is FileList is a list of file objects. On behalf of the user to select all the files. Let's look at a simple demo, which properties have a look at the file object. The following code:

<!DOCTYPE html>
<html>
  <head>
    <title>filesystem:URL</title>
  </head>
  <body>
    <div>
      <label>选择:</label>
      <input type='file' multiple id="file" />
      <input type="button" value="文件上传" onClick="showFile()" />
    </div>
    <script>
      function showFile() {
        var files = document.getElementById('file').files;  // 返回所有被选择的文件
        for (var i = 0, ilen = files.length; i < ilen; i++) {
          // 打印出单个文件对象的信息
          console.log(files[i]);
          /*  
           * 打印的信息如下:
           File {
            lastModified: 1457946612000
            lastModifiedDate: Mon Mar 14 2016 17:10:12 GMT+0800 (CST) {}
            name: "test.html"
            size: 796
            type: "text/html"
            webkitRelativePath: "" 
          */
          /*  如果上传的是一张图片的话,会返回如下信息的
            File {
              lastModified: 1466907500000
              lastModifiedDate: Sun Jun 26 2016 10:18:20 GMT+0800 (CST) {}
              name: "a.jpg"
              size: 23684
              type: "image/jpeg"
              webkitRelativePath: ""
            }
          */
          /*
           因此 如果需要判断该上传的文件是不是图像文件的话,可以根据type类型来判断如下:
           var file = files[i];
           if (!/image\/\w+/.test(file.type)) {
              console.log('该文件不是图像文件');
           } else {
              console.log('该文件是图像文件');
           }

           但是如果只让传图片的话,可以在image控件添加一个属性 accept="image/*" 即可;我们可以如下写代码:
           <input type='file' multiple accept = 'image/gif,image/jpeg,image/jpg,image/png' />
           */
        }
      }
    </script>
  </body>
</html>

2. Understand Blob object

Important: HTML5, add a Blob object representing the original binary data file object is actually inherited the Blob object.
Blob object has two properties, size attribute bytes representing the length of a Blob object, the Blob type attribute indicates the MIME type, if the type is unknown, a null string is returned.

Consider the following code:

<!DOCTYPE html>
<html>
  <head>
    <title>filesystem:URL</title>
  </head>
  <body>
    <div>
      <label>选择文件:</label>
      <input type="file" id="file" />
      <input type="button" value="显示文件信息" onClick="showFileType()" />
      <p>文件字节长度: <span id="size"></span></p>
      <p>文件类型:<span id="type"></span></p>
    </div>
    <script>
      function showFileType() {
        var file;
        // 获取用户选择的第一个文件
        file = document.getElementById('file').files[0];
        var size = document.getElementById('size');
        var type = document.getElementById('type');
        // 显示文件字节的长度
        size.innerHTML = file.size;
        // 显示文件的类型
        type.innerHTML = file.type;

        // 打开控制台 查看返回的file对象
        console.log(file);
      }
    </script>
    
  </body>
</html>

Note: File Blob and can be used simultaneously, may be used to read data from FileReader the Blob.
Below are some pictures address the absolute path into a base64 encoded picture, and then convert the images into base64-encoded blob object. code show as below:

<!DOCTYPE html>
<html>
  <head>
    <title>将以base64的图片url数据转换为Blob</title>
  </head>
  <body>
    <script>
      /**  
       * 将以base64的图片url数据转换为Blob  
       * @param urlData  
       * 用url方式表示的base64图片数据  
       */  
      function convertBase64UrlToBlob(base64){ 
        var urlData =  base64.dataURL;
        var type = base64.type;
        var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
        //处理异常,将ascii码小于0的转换为大于0  
        var ab = new ArrayBuffer(bytes.length);  
        var ia = new Uint8Array(ab);  
        for (var i = 0; i < bytes.length; i++) {  
            ia[i] = bytes.charCodeAt(i);  
        }  
        return new Blob( [ab] , {type : type});  
      }
      /* 
       * 图片的绝对路径地址 转换成base64编码 如下代码: 
       */
      function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
        var dataURL = canvas.toDataURL("image/"+ext);
        return {
          dataURL: dataURL,
          type: "image/"+ext
        };
      }
      var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
      var image = new Image();
      image.crossOrigin = '';
      image.src = img;
      image.onload = function(){
        var base64 = getBase64Image(image);
        console.log(base64);
        /*
         打印信息如下:
         {
          dataURL: "data:image/png;base64,xxx"
          type: "image/jpg"
         }
         */
        var img2 = convertBase64UrlToBlob(base64);
        console.log(img2);
        /*
         打印信息如下:
         Blob {size: 9585, type: "image/jpg"}
         */
      } 
    </script>
  </body>
</html>

Note: In HTML5, add a Blob object representing the original binary data file object is actually inherited the Blob object. Therefore, we can use the absolute address into a picture file object.

So we can use the absolute address convert the picture into the file object, the developer gave me the only picture of an absolute address, so we always wanted to how pictures absolute address into a file object, if you do not turn into a file object, use this sentence code when var reader = new FileReader (); will complain, so you can use the above told us blob blob object is first converted into an object, then you can use the file operation object fileReader.

Guess you like

Origin www.cnblogs.com/jessie-xian/p/11597763.html