vue upload image to base64, binary array, save encoded data to file

functional requirement

1. Picture to base64

2.base 64 to binary array

3. Save binary data to file and download to local

resolvent

Question 1:

reference material

vue element upload picture to base64

Specific code

getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
}
beforeUpload(file) {
    this.getBase64(file).then(res => {
        console.log(res);
   })
}

Question 2

reference material

base 64 to bytes array

Specific code

    beforeUpload(file) {
      var fileName = file.name || ''

      this.getBase64(file).then(res => {
        // console.log(res);
 
        //Binary array conversion
        var bytes = window.atob(res.split(',')[1]);        //Remove url And convert to byte

        //Handling exceptions,take ascii Convert code less than 0 to greater than 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);
        }

        console.log("ia", ia)
      });
}

Question 3

reference material

Save the data in memory as a file and download it locally

Specific implementation

Method 2 in reference

Specific code

  function  downFile(json1) {
      var elementA = document.createElement('a');

      elementA.setAttribute('href', 'data:text/plain;charset=utf-8,' + json1);
      elementA.setAttribute('download', +new Date() + ".txt");
      elementA.style.display = 'none';
      document.body.appendChild(elementA);
      elementA.click();
      document.body.removeChild(elementA);
    },

 beforeUpload(file) {
      var fileName = file.name || ''

      this.getBase64(file).then(res => {
        // console.log(res);
        //Binary array conversion
        var bytes = window.atob(res.split(',')[1]);        //Remove url And convert to byte

        //Handling exceptions,take ascii Convert code less than 0 to greater than 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);
        }
        this.downFile(ia)
        console.log("ia", ia)
      });
}

Keywords: Javascript less ascii Vue

Added by error_22 on Fri, 29 May 2020 17:49:11 +0300