SoFunction
Updated on 2025-04-05

Vue project takes photos or uploads pictures and converts them to base64 format

Vue project takes photos or uploads pictures and converts them to base64 format

need

In the vue project, H5 clicks the button to trigger uploading pictures or photo uploading. The uploaded pictures are transmitted to the background using base64 bits, and finally realizes the ID card photo recognition function.

Implementation process

(1) Set a button and a hidden input. Clicking the button is the trigger button to upload pictures and take photos.

<div>
   <input  type="file"  ref="file" accept="image/*" hidden @change="onInputChange($event)" /> 
    <div @click="triggerUpload">
         <img src="@res/images/scenicSpots/" />
         <span>Upload pictures</span>
     </div>
</div>

(2) Convert the uploaded image to base64 format

//Click on the image to trigger file uploadtriggerUpload() {
   $("#filePhoto").click();
},
//Upload the file to the browser triggers the eventonInputChange(el) {
  var self = this;
  var file = [0];
  (file)
  var type = ('/')[0];
  if(type === 'image') {
    //Convert the image to base64    var reader = new FileReader();
    (file); // readAsDataURL method can convert the uploaded image format to base64, and then store it in the image path.     = function () {
        var image = ;  // image is base64 format, and the backend request is passed in image    }
  }else{
    self.$('Please upload the picture correctly');
  }

},

vue image upload component, including base64, binary upload and image rotation

Many of the vue projects I have recently done involve image uploads, and we have summarized them in order to facilitate development.

Because the company has many projects and uses different background languages, some need to be passed through base64 strings, some need to be converted into binary data streams, and some can be submitted directly using the from form. Later, there was a problem that the picture will rotate when taking photos on iOS, and it was also packaged.

OK, don't say much nonsense and just upload the code.

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="utf-8" />
    <title>Image upload</title>
</head>
 
<body>
    <form >
        <input type='file' accept="image/*" name="avatar" placeholder=""  />
    </form>
    <img src="" alt="" id='preImg'>
    <!-- Need to introduce plug-ins -->
    <script src='./'></script>
    <script>
        
        var domImg = ('#img')
        //Add DOM Event         = function upLoadImg(e, type) {
            let files =  || ;
            if (!) return;
            if (files[0].("image") < 0) {
                alert("Uploaded non-picture");
                return;
            }
            if (files[0].size > 5 * 1000000) {
                alert("Uploading files too large");
                return;
            }
            
            // Picture compression into base64            compress(, (base64, imgFile) => {
                var upImage = new FormData();
                ("fileName", );
                var blob = convertImgDataToBlob(base64);
                ("file", blob);
 
                //Upload image interface                this.$http({
                    method: "POST",
                    url: ,
                    body: upImage
                }).then(
                    res => {
                        (res);
                    },
                    err => {
                        (err);
                    }
                );
            });
            
            //Convert base64 to binary function            function convertImgDataToBlob(base64Data) {
                var format = "image/jpeg";
                var base64 = base64Data;
                var code = ((",")[1]);
                var aBuffer = new ();
                var uBuffer = new window.Uint8Array(aBuffer);
                for (var i = 0; i < ; i++) {
                    uBuffer[i] = (i) & 0xff;
                }
                var blob = null;
                try {
                    blob = new Blob([uBuffer], {
                        type: format
                    });
                } catch (e) {
                     =
                         ||
                         ||
                         ||
                        ;
                    if ( == "TypeError" && ) {
                        var bb = new ();
                        ();
                        blob = ("image/jpeg");
                    } else if ( == "InvalidStateError") {
                        blob = new Blob([aBuffer], {
                            type: format
                        });
                    } else {}
                }
                return blob;
            }
            
            //Compress the image into base64 function            function compress(event, callback) {
                //Picture direction angle                var Orientation = null;
                var file = [0];
                var reader = new FileReader();
 
                //Get the photo direction angle attribute, user rotation control                (file, function() {
                    (this);
                    Orientation = (this, 'Orientation');
                });
 
                 = function (e) {
                    var image =("img");
                     = function () {
                        //Repaint the picture with canvas                        var canvas = ("canvas");
                        var x = ;
                        var y = ;
                         = 375 * 2;
                         =  / x * y;
                        var width = ;
                        var height = ;
                         = ;
                         = ;
                        var context = ("2d");
                        (0, 0, width, height);
                        //Rotate the picture                        switch (Orientation) {
                            case 3:
                                (180 *  / 180);
                                (this, -, -, , );
                                break;
                            case 6:
                                (90 *  / 180);
                                (this, 0, -, , );
                                break;
                            case 8:
                                (270 *  / 180);
                                (this, -, 0, , );
                                break;
                            case 2:
                                (, 0);
                                (-1, 1);
                                (this, 0, 0, , );
                                break;
                            case 4:
                                (, 0);
                                (-1, 1);
                                (180 *  / 180);
                                (this, -, -, , );
                                break;
                            case 5:
                                (, 0);
                                (-1, 1);
                                (90 *  / 180);
                                (this, 0, -, , );
                                break;
                            case 7:
                                (, 0);
                                (-1, 1);
                                (270 *  / 180);
                                (this, -, 0, , );
                                break;
                            default:
                                (this, 0, 0, ,);
                        }
 
                        var quality = 0.9; //Compression degree                        var data;
                        var result;
                        var length;
                        //Control the size of the image upload. Note that if the image is too large, the parameter is null error will appear when uploading ajax.                        // If the picture is too large, the image compression level will be enlarged.                        do {
                            data = ("image/jpeg", quality);
                            length = ;
                            result = (length / 4 * 3 + 1023) / 1024; //Calculate the size of the compressed image                            quality -= 0.05;
                        } while (result > 450);
                        //data:base64
                        ('#preImg').src = data
                        callback(data, [0]);
                    };
                     = ;
                };
                (file);
            }
        }
    </script>
</body>
 
</html>

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.