Share a feature to preview images through input file

  • Another little knowledge, take notes!!
$("#fuPoster").change(function (event) {
        // Get the HTML5 JS object of the file based on this 
        var files = event.target.files, file;
        if (files && files.length > 0) {
            // Get the file currently uploaded
            file = files[0];
            // What is this object in the console
            console.log(file);
            // Then we can do some actions like file size verification
            if (file.size > 1024 * 1024 * 5) {
                alert('Picture size cannot exceed 5MB! ');
                return false;
            }
            / /!!!!!!!!!!!!!!!
            // The key is to generate a usable image URL from the file object
            // Get the window URL tool
            var URL = window.URL || window.webkitURL;
            // Generate the destination URL from file
            var imgURL = URL.createObjectURL(file);
            $("#imgPoster").attr("src", imgURL); }})Copy the code
  • Guys, with the preview, it’s natural to do an avatar change

The idea is that if you have previewed the image with the code above, you can get the SRC of the image, and then you can replace this SRC with the img that needs to be replaced.