Upload, download and compress pictures

Blob

Create Blob instance objects

Properties of a Blob object

Blob instance

File

URL

URL.createObjectURL(blob:Blob)

URL.revokeObjectURL(objectURL)

FileReader

Create the FileReader instance object

Commonly used attributes

Common event

Commonly used method

Image upload

Upload pictures directly

The image is compressed and uploaded


Upload, download and compress pictures

Blob

****Blob (Binary Large Object) objects represent a piece of Binary data and provide a series of operation interfaces. Other apis for manipulating binary data, such as File objects, are built on top of Blob objects, inheriting their properties and methods.

Create Blob instance objects

The Blob constructor, which takes two arguments. The first argument is an array containing the actual data, which can be a DOMString or an ArrayBuffer, and the second argument is the type of the data, neither of which is required.

var blob = new Blob(["Hello World"] and {type: 'text/html'});
Copy the code

Properties of a Blob object

  • The size attribute
var blob = new Blob(["Hello World"] and {type: 'text/html'});
console.log(blob.size) / / 11
Copy the code
  • The type attribute
var blob = new Blob(["Hello World"] and {type: 'text/html'});
console.log(blob.type) // text/html
Copy the code

Blob instance

// Create a Blob instance object and download the file via the hyperlink
var blob = new Blob(["Hello World"] and {type: 'text/html'});
var elink = document.createElement("a");
elink.href = window.URL.createObjectURL(blob);
elink.download = "hello-world.txt";
elink.textContent = "Download File!";
document.body.appendChild(elink);
Copy the code

File

In JavaScript, File inherits from Blob. The File extends Blob; The most common scenario is when a file is uploaded through . The File instance object has three commonly used attributes: Name (File name) size(File size, in bytes) Type (MIME type of the File)

<html>

<body>
    <input type="file" id="fileInput" name="file" multiple="multiple" />
</body>

</html>

<script>
    var fileList = [] // File array collection
    var fileInput = document.getElementById("fileInput")
    fileInput.addEventListener("change".function (event) {
        var file = fileInput.files[0] // Get File information File instance object
        fileList.push(file)
        console.log(file)
    })
</script>
Copy the code

URL

The most common scenario is to convert a binary file to a URL that can be placed anywhere a URL would normally be placed, such as the SRC attribute of the IMG tag.

URL.createObjectURL(blob:Blob)

<html>

<body>
    <input type="file" id="fileInput" name="file" multiple="multiple" />
</body>

</html>

<script>
    var fileList = []; // File array collection
    var fileInput = document.getElementById("fileInput")
    fileInput.addEventListener("change".function (event) {
        var file = fileInput.files[0] // File
        fileList.push(file)


        // url.createObjecturl (Blob: Blob) Binary data transfer URL
        var imgUrl = URL.createObjectURL(file) // File is an instance of file. File inherits from Blob, so file is also an instance of Blob
        var img = new Image() // Create an Image instance object
        img.src = imgUrl
        img.onload = () = > {
            document.body.appendChild(img)
        }
    });
</script>
Copy the code

URL.revokeObjectURL(objectURL)

Removing the transformed URL frees the URL.

<html>

<body>
    <input type="file" id="fileInput" name="file" multiple="multiple" />
</body>

</html>

<script>
    var fileList = []; // File array collection
    var fileInput = document.getElementById("fileInput")
    fileInput.addEventListener("change".function (event) {
        var file = fileInput.files[0] // File
        fileList.push(file)


        // Download the image
        var elink = document.createElement('a')
        var downloadUrl = URL.createObjectURL(file)
        elink.href = downloadUrl
        elink.download = file.name // Set the file name
        elink.textContent = ' '
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(downloadUrl) / / remove url
        document.body.removeChild(elink)
    })
</script>
Copy the code

FileReader

Blob objects and File objects are only containers for binary data and cannot manipulate binary by themselves. FileReader objects are specifically designed to manipulate binary data.

Create the FileReader instance object

var fileReader = new FileReader()
Copy the code

Commonly used attributes

  • Result: Indicates the file content. This property is valid only after the read operation is complete.

Common event

  • Onload: processingloadEvents. This event is emitted when the read operation is complete.

Commonly used method

  • ReadAsDataURL () : Starts reading the specifiedBlobThe content of. Once that’s done,resultThe property will contain an ****data:URL Format string to represent the contents of the file being read; At this timeresultProperty can act as a URL, similar to the url generated by url.createObjecturl (Blob: Blob) when the two urls are different.
<html>

<body>
    <input type="file" id="fileInput" name="file" multiple="multiple" />
</body>

</html>

<script>
    var fileList = []; // File array collection
    var fileInput = document.getElementById("fileInput")
    fileInput.addEventListener("change".function (event) {
        var file = fileInput.files[0] // File
        fileList.push(file)

        // FileReader 
        var fileReader = new FileReader()
        fileReader.readAsDataURL(file)  // Read the file. After reading the file, the contents of the file will be put in the result property as data: URL
        fileReader.onload = () = > {     // onload: after the file is read
            // Display the image
            var img = new Image() / / Image object
            img.src = fileReader.result // Set image SRC to the result attribute of fileReader
            img.onload = () = > {
                document.body.appendChild(img)
            }
        }
    })
</script>
Copy the code

Image upload

Upload pictures directly

Take the File instance object and upload it directly.

<template>
  <div class="about">
    <input
      type="file"
      id="fileInput"
      name="file"
      multiple="multiple"
      @change="uploadImg"
    />
  </div>
</template>
<script>
import { defineComponent, getCurrentInstance } from "vue";
export default defineComponent({
  name: "About".setup() {
    const { proxy } = getCurrentInstance();
    function uploadImg() {
      var fileInput = document.getElementById("fileInput");
      var file = fileInput.files[0];
      var formData = new FormData();
      formData.append("imgFile", file);
      proxy.$axios
        .post("/avatar/upload", formData) // Network request
        .then((result) = > {
          console.log(result);
        })
        .catch(() = > {
          / * * /})}return {
      uploadImg
    }
  }
});
</script>
Copy the code

The image is compressed and uploaded

After the image is compressed, it can be converted to a File instance object and then transferred to the interface.

<template>
  <div class="about">
    <input
      type="file"
      id="fileInput"
      name="file"
      multiple="multiple"
      @change="uploadImg"
    />
  </div>
</template>
<script>
import { defineComponent, getCurrentInstance } from "vue";
export default defineComponent({
  name: "About".setup() {
    const { proxy } = getCurrentInstance();
    function uploadImg() {
      var fileInput = document.getElementById("fileInput");
      var file = fileInput.files[0];
	  var blob = dataURLtoBlob(tobase64(file)); // Compress the image
      var aasfile = blobToFile(blob, file["name"]); / / base64 Blob
      var imgFile = new File([aasfile], file["name"] and {// Blob 转File
        type: "image/jpeg"});var formData = new FormData();
      formData.append("imgFile", imgFile); 
      proxy.$axios.post("/avatar/upload", formData) // Network request
        .then((result) = > {
             console.log(result);
        }).catch(() = > {
             console.log("error");
        });
    }


   /* * parameter blob: blob (File) instance object, i.e. FileReader converts the Blob instance object (binary data object) to a URL and assigns the SRC attribute of the Image instance object. * 2. Draw a picture using the drawImage method of Canvas, and finally perform Base64 compression using the toDataURL() method of Canvas to return DataURL */
    function tobase64(blob) {
        var fileReader = new FileReader()
        fileReader.readAsDataURL(blob)
        fileReader.onload = () = > {     // onload: event after the file is read
            var img = new Image()
            img.src = fileReader.result
            img.onload = () = > {
                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d') // Graph brush
                const width = img.width
                const height = img.height 
                canvas.width = width    // Canvas width = image width
                canvas.height = height  Canvas height = image height
                ctx.drawImage(img, 0.0, width, height)
                const dataURL = canvas.toDataURL('image/jpeg'.0.6) // Second argument: The smaller the value, the more blurry the compressed image
                // console.log(dataURL)
                / / the document. The body. The appendChild (canvas) / / show a good image
                return dataURL
            }
        }
    }

    // Convert Base64 to bloB parameter dataUrl: compressed dataUrl
    function dataURLtoBlob(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 });
    }

    // Convert blob to file
    function blobToFile(theBlob, fileName) {
      theBlob.lastModifiedDate = new Date(a); theBlob.name = fileName;return theBlob;
    }

    return{ uploadImg, }; }});</script>
Copy the code