Detailed explanation of window.URL.createObjectURL() and window.URL.revokeObjectURL

1.URL.createObjectURL

The URL.createObjectURL() method will create a URL pointing to the parameter object based on the passed parameters. The URL's life only exists in the document it was created in. The new object URL points to the executed File object or Blob object.

 

grammar:  

objectURL = URL.createObjectURL(blob || file);

 

 

parameter:

File object or Blob object

Here is roughly the File object and Blob object:

A File object is a file. For example, if I use the input type="file" tag to upload a file, then each file in it is a File object.

A Blob object is binary data. For example, an object created by new Blob() is a Blob object. For another example, in XMLHttpRequest, if the responseType is specified as blob, the returned value is also a blob object.

 

be careful:

Every time you call createObjectURL, a new URL object is created. Even if you have already created a URL for the same file. If you no longer need the object, to release it, use the URL.revokeObjectURL() method. The browser automatically frees the page when it is closed, but for best performance and memory usage, it should be freed when it is guaranteed to be no longer needed.

 

Two.URL.revokeObjectURL

The URL.revokeObjectURL() method will release an object URL created by URL.createObjectURL(). When you want to have used the object URL and let the browser know that the URL no longer needs to point to the corresponding file, You need to call this method.

The specific meaning is that an object URL can be used to access the specified file, but I may only need to access it once. Once it has been accessed, the object URL is no longer needed, and is released. After release, the object URL no longer points to the specified file.

For example, for a picture, I created an object URL, and then through this object URL, I loaded the picture in my page. Since it has been loaded, and I don't need to load the picture again, then I release the object URL, Then the URL no longer points to the image.

 

grammar:

window.URL.revokeObjectURL(objectURL);

 

parameter:

objectURL is an object URL created by the URL.createObjectURL() method.

 

These two methods do not support lower version browsers.

 

Finally, give a comprehensive chestnut:

Get a picture through ajax and display it on the page.

html: 

<body>
    <button id="getPic">get the picture Blob data</button>
</body>

 

js:

//Get image Blob data
      document.getElementById('getPic').onclick = function(e){
        $.ajax({
          type:'GET',
          url:'img.png',
          resDataType:'blob',
          imgType:'png',
          success:function(resText,resXML){
            var img = document.createElement('img');
            var objectUrl = window.URL.createObjectURL(resText);
            img.src = objectUrl;
            img.onload = function(){
              window.URL.revokeObjectURL(objectUrl);
            };
            document.body.appendChild(img);
          },
          fail:function(err){
            console.log(err)
          }
        });
        e.preventDefault();
      }

Specifies that the returned data format is blob binary data.

Creates an object URL from the returned image binary data.

Release the object URL when the image is loaded.

 

ajax.js:

var $={};
$.ajax = function(options){
    //1. Get parameters
    var type = options.type.toUpperCase() || 'GET';
    var resDataType = options.resDataType || 'string';
    var reqDataType = options.reqDataType || 'string';
    var url = options.url;
    var data = options.data;
    var success = options.success;
    var fail = options.fail;
    var progress = options.progress;
    var imgType = options.imgType || 'jpg';

    //2. Get the xhr object
    var xhr = $.getXhr();

    //3. Establish a connection
    xhr.open(type,url);
    /*Specify the format of the returned data before sending the request*/
    if(resDataType==='blob'){
        xhr.responseType = 'blob';
    }

//4. Send the request
    if(type==='GET'){
        xhr.send(null)
    }
    else if(type==='POST') {
        if(progress){
            xhr.upload.onprogress = progress;
        }
        if(reqDataType==='json'){
            xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8');
            data = JSON.stringify(data);  //Only json in string format can be sent, json cannot be sent directly
        }
        if(reqDataType==='string'){
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        }
        xhr.send(data);
    }

    //5. Receive data
    xhr.onreadystatechange = function(){
        if(this.readyState===4 && (this.status>=200 && this.status<300)){
            var res;
            if(resDataType==='json'){
                res = JSON.parse(this.responseText);
                success.call(this,res,this.responseXML)
            }
            if(resDataType==='blob'){
                res = new Blob([this.response],{type:'image/'+imgType});
                success.call(this,res)
            }

        }
    };
};

Specifies that the format of the response is binary data.

Use xhr.response to get the binary data of the response, not xhr.responseText. When xhr.responseType='blob' is defined, xhr has no responseText property.

Although new Blob() is used here, it is not necessary to return xhr.response directly, which is also correct.

 

Reference text: https://developer.mozilla.org/en-US/docs/Web/API/URL.revokeObjectURL 

Tags: Javascript

Posted by Dan400007 on Mon, 30 May 2022 07:39:24 +0530