Home > Web Front-end > JS Tutorial > body text

Detailed explanation of converting the absolute path of an image into a file object in HTML5

小云云
Release: 2018-01-13 11:15:19
Original
8047 people have browsed it

This article mainly introduces how to convert the absolute path of an image into a file object in HTML5. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Convert the absolute path of the image into base64 encoding, please read this article

Let’s first understand the basic knowledge points:

1. Understand the HTML5 FileList object and file object.

In HTML5, the FileList object represents a list of files selected by the user. By adding the multipe attribute, multiple files can be selected at once within the file control. Each user-selected file in the control is a file object, and the FileList object is a list of file objects. Represents all files selected by the user. Let's first look at a simple demo to see what attributes the file object has. The following code:


<!DOCTYPE html>
<html>
  <head>
    <title>filesystem:URL</title>
  </head>
  <body>
    <p>
      <label>选择:</label>
      <input type=&#39;file&#39; multiple id="file" />
      <input type="button" value="文件上传" onClick="showFile()" />
    </p>
    <script>
      function showFile() {
        var files = document.getElementById(&#39;file&#39;).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(&#39;该文件不是图像文件&#39;);
           } else {
              console.log(&#39;该文件是图像文件&#39;);
           }

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

2. Understanding the Blob object

Key points: In HTML5, a new Blob object is added to represent the original Binary data, in fact, the file object also inherits the Blob object.

The Blob object has two attributes. The size attribute represents the byte length of a Blob object, and the type attribute represents the MIME type of the Blob. If it is an unknown type, an empty string is returned.

Please see the following code:


<!DOCTYPE html>
<html>
  <head>
    <title>filesystem:URL</title>
  </head>
  <body>
    <p>
      <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>
    </p>
    <script>
      function showFileType() {
        var file;
        // 获取用户选择的第一个文件
        file = document.getElementById(&#39;file&#39;).files[0];
        var size = document.getElementById(&#39;size&#39;);
        var type = document.getElementById(&#39;type&#39;);
        // 显示文件字节的长度
        size.innerHTML = file.size;
        // 显示文件的类型
        type.innerHTML = file.type;

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

Note: Blob and File can be used at the same time, and FileReader can be used to read data from the Blob.

The following is an absolute path image address converted into a base64-encoded image, and then the base64-encoded image is converted into a blob object. The code is as follows:


<!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(&#39;,&#39;)[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 = &#39;&#39;;
      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>
Copy after login

Note: In HTML5, a new Blob object is added to represent the original binary data. In fact, the file object also inherits the Blob object. Therefore we can use the absolute address of the image to convert it into a file object.

So we can use the absolute address of the picture to convert it into a file object. For a detailed demo, you can see the picture upload control on my git. The plug-in first supports picture upload, and then suddenly found that when the edit page is reached, it needs to be displayed. The default image can also support uploading new images while displaying images by default, or deleting all images. However, the developer only gave me the absolute address of the image, so I have always wanted to convert the absolute address of the image into file object, if it is not converted into a file object, when using this code, var reader = new FileReader(); will report an error, so you can use the blob object we talked about above to convert it into a blob object first, and then you can use the file operation object fileReader.

Related recommendations:

Javascript converts the absolute path of the image into base64 encoding

How to use the absolute path and relative path of html

Detailed analysis of the difference between HTML relative paths and absolute paths

The above is the detailed content of Detailed explanation of converting the absolute path of an image into a file object in HTML5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template