1. The background

In this public number project, the need for a user’s small program TWO-DIMENSIONAL code, at the beginning of the thought is real-time generation of small program two-dimensional code, the background asked me whether I can vaguely remember wechat seems to provide this function, so I agreed. At first I thought ACCESS_tojen was all I needed to generate it myself, but I seemed to have overlooked the cross-domain aspect. Well, I guess we’re gonna have to make a backstage transfer. Since the background is not available at the moment, I will use AppID and Secret to try the effect by myself.

The getWXACodeUnlimit document says:

The binary content of the image is returned directly if the call is successful, and JSON data is returned if the request fails.

2. Here’s the problem

What is binary content? ArrayBuffer or Blob? Try them all.

Vaguely remember that XHR2 can now fetch data in other formats from the server.

value The data type
‘ ‘ DOMString (this is the default type)
arraybuffer ArrayBuffer object
blob A Blob object
document The Document object
json JavaScript object, parsed from a JSON string returned by the server
text DOMString

I initially thought that if I set responseType to Blob, it would return a string. At that time can really be a fierce operation such as tiger, a look at the result 250.

Looking at the constructor property of the response data gives you an idea of the type of returned data, which is embarrassing to forget.

Without further ado, here’s my solution.

3. Use Blob as SRC for the image

There are three ways to do this (_blob is the Blob object obtained by an Ajax request) :

3.1 Using the window.URL method

var src = window.URL.createObjectURL(blob);
document.querySelector("#img").setAttribute("src", src)

// createObjectURL creates data that will not be released by itself, so if it is not useful, you have to call the following method to release it manually
window.URL.revokeObjectURL(src)
Copy the code

3.2 Using FileReader

var reader = new FileReader();
reader.onload = (e) = > {
  document.querySelector("#img").setAttribute("src", reader.result)
}
reader.readAsDataURL(_blob);
Copy the code

3.3 Directly Set the interface Address to SRC

/ / assume that the address of the interface is HTTP: / / http://test.com/index/getWxImg / / HTML < img SRC = "http://test.com/index/getWxImg" Alt = "WeChat applet qr code" / >Copy the code

This is equivalent to accessing the image directly from the URL in the browser’s address bar, and it is automatically displayed based on the content-Type and response data of the response header. Of course, this method is limited to GET requests, and the first two methods can only be used if the interface requests only post.

Having made a big mistake, I decided to take a closer look at ArrayBuffers and BLOBs.

4

4.1 ArrayBuffer(Binary Array)

Binary arrays (ArrayBuffer objects, TypedArray views, and DataView views) are an interface for JavaScript to manipulate binary data. The original design purpose of this interface is related to the WebGL project. The so-called WebGL is the communication interface between browser and graphics card. In order to meet the massive and real-time data exchange between JavaScript and graphics card, the data communication between them must be binary instead of the traditional text format. The text format passes a 32-bit integer, and the JavaScript scripts and graphics cards at both ends have to convert the format, which is very time-consuming. If there were a mechanism to manipulate bytes directly, as in C, and feed 4-byte 32-bit integers into the graphics card in binary form, script performance would be greatly improved.

4.2 Blob(Binary Data)

A Blob object represents an immutable, raw data-like file object. Blobs don’t necessarily represent data in JavaScript’s native format. The File interface is based on Blob, inheriting the functionality of Blob and extending it to support files on the user’s system.

The constructor of a Blob is Blob(blobParts[, options]). The first argument must be an array, either a string array or a binary array. Options is an object that specifies the content-type of a file by setting the type value.

Simply put, you can treat an ArrayBuffer as a binary array and a Blob as binary data. (Is that right? If you don’t understand, please correct me.

5. Conversion of BLOBS to other data types

5.1 Converting Base64 to Blob

function dataURL2Blob(dataurl) {
  var arr = dataurl.split(', '), mime = arr[0].match(/ : (. *?) ; /) [1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
Copy the code

5.2 Converting a String to Blob

function plain2Blob(text, type) {
  return new Blob([text], { type: 'text/plain' });
}
Copy the code

5.3 Converting an ArrayBuffer into a Blob

function buffer2Blob(_buffer, type) {
  return new Blob([_buffer], { type: 'application/octet-stream' });
}
Copy the code

5.4 Changing bloBs to other types

The only way to read from the Blob is to use FileReader.

var _blob = new Blob([]); Var reader = new FileReader(); reader.onload = (e) => { console.log(reader.result) }Copy the code
  1. Into base64:reader.readAsDataURL(_blob);
  2. Into the text:reader.readAsText(_blob);
  3. To arrayBuffer:reader.readAsArrayBuffer(_blob);

6. Download files using Blob

6.1 Downloading Functions

// @params content: String
// @params type: String
// @params filename: String
function downloadFile(content, type = 'text', filename) {
  var textBlob;
  if (type === 'img') {
    textBlob = dataURL2Blob(content);
    if(! filename) {throw new Error('When type is img, filename filename parameter must be passed'); }}else {
    textBlob = plain2Blob(content, type);
    filename = filename || generateFilename(type);
  }

  var a = document.createElement("a"),
      href = URL.createObjectURL(textBlob);
  a.href = href;
  a.download = filename;
  document.body.appendChild(a);
  a.click();

  document.body.removeChild(a);
  URL.revokeObjectURL(href);
}

function dataURL2Blob(dataurl) {
  var arr = dataurl.split(', '), mime = arr[0].match(/ : (. *?) ; /) [1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

function plain2Blob(text, type) {
  var fileTypes = {
    text: 'text/plain'.svg: 'image/svg+xml',}return new Blob([text], { type: fileTypes[type] || 'application/octet-stream'})}function generateFilename(type) {
  var prefixs = {
    text: 'txt'.svg: 'svg',}return '1. + (prefixs[type] || '.txt')}Copy the code

6.2 test

// Download the TXT file
downloadFile('tests the second line \r\n'.'text'.)/ / download SVG
downloadFile(` < SVG version = "1.1" id = "tuceng_1" XMLNS = "http://www.w3.org/2000/svg" XMLNS: xlink = "http://www.w3.org/1999/xlink" x = 0 px "" y="0px" width="80px" height="36px" viewBox="0 0 80 36" enable-background="new 0 0 80 36" xml:space="preserve"> 
      
        < / SVG > `
      .'svg'.'1.svg')

// Download the image
var data = 'data:image/png; base64,iVBORw0KGgoAAAANSUhEUgAAAQQAAAEECAIAAABBat1dAAAGi0lEQVR4nO3dwa7jNgwF0KTo///y6+Yii7Ex1bAi5aDnLAeJ7STvQhiCot4/Pz8v4 PX66/QDwFMIA4QwQAgDhDBA/H39p/f7Pf8cH9fqVu15Vq5ztpJ2+7ke+Ehb7PpZd7n9nq0MEMIAIQwQwgAhDBA31aSrvhLHrkpR7cqTd1/8Dmtv7HvXriuvO P5nZmWAEAYIYYAQBghhgFiqJl2dLRfUShy1u1/v1VpgqfXw9FV4+q7Td6/yn5mVAUIYIIQBQhgghAGiWE2a1FeD2nX3jXvo+rqMJutUXzqMy8o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a UXf5KJdlavJDWJlfbvG+sbNr+h718a2NCsDhDBACAOEMEAIA8S2atLV01pfVuwaJVQuy0weBLhy9+G9Zlvubm4S/FfCACEMEMIAIQwQN3OTbl7U1iLS19F0N Tkru/y5+tquzl558kcsszJACAOEMEAIA4QwQBSrSX21o13OdkaVP2nfgXGTX8jktsfa89yyMkAIA4QwQAgDhDBA3Ox0W/kP+9myw67X9D1Pq77KzNkGs76C5 OLzWBkghAFCGCCEAUIYIG56k55WCujrntq4SWrL89x6WhtY3x9MX01skZUBQhgghAFCGCCEAaI4hXvXIOi+7Ve7WlZqpZvj/Us1Z6cbTbaT3bIyQAgDhDBAC AOEMEAUq0m7qkDPn5u0UqyY7Hrqvvgvzs47Gm45szJACAOEMEAIA4QwQCxN4T7r7HifySHYey9VMLnxcNfz1JibBL8jDBDCACEMEMIAUZzC3ae2a+z5NbFFk 0fs7TK57VFvEkwQBghhgBAGCGGAWNrpdrYZ5qpvutHKu3a5fea+2/VtTmxt1ircvczKACEMEMIAIQwQwgAxOoX77HanyTJIucSx8pC7OpHOHnJX07dd8WVlg A9hgBAGCGGAEAaIYjXprL6T4Go2br+qXapWBdpVldq1OXFXua/801sZIIQBQhgghAFCGCC+spp01be1anKD2OLLJrcH9l3ngbvqrAwQwgAhDBDCACEMEDdnu p3dAPWNm61W7rXxTLeavvneZzuRVqgmwZ8RBghhgBAGCGGAWKomTZoczlxra+nrg1q8eO12u76is+W+1sP7rAwQwgAhDBDCACEMEDfVJPh/sjJACAOEMEAIA 4QwQAgDxD+aYuUyl4qrbgAAAABJRU5ErkJggg==';
downloadFile(data, 'img'.'1.png')
Copy the code

6.3 Downloading Function Description

Currently, only text files, SVG, and images are supported.

7 summary

Blobs are useful, to the extent that files can be uploaded or downloaded directly from the front end.

File is also inherited from Blob, so the generated image Blob can also be directly uploaded via Ajax for storage such as OSS. I used Blob to upload the first image of PPT to OSS.