Native JS realizes image upload preview

The principle of front-end js to achieve image upload is to define the input tag as an uploaded file through the type=file attribute of the input tag, and monitor the onchange event of the input. When the value of the input changes, it means that the user has uploaded the image, and the value of the input The value is the relative path of the image uploaded by the user, create a new FileReader object, convert the image into base64 format encoding ( multipart/form-data is used for forms, and base64 can be passed without adding hidden ), dynamically create img tags and convert the encoded encoding Assign it to the src attribute of the img tag.

h5 page uses native JS to achieve image upload preview function

<ul class="weui-uploader__files" id="uploaderFiles">
    <li class="weui-uploader__file">
        <img src="/statics/front/images/picture02.jpg"/>
        <input type="hidden" name="files[]" value="value="data:image/jpeg;base64,/9j/4QAY"/>
        <i class="weui-icon-cancel"></i>
    </li>
</ul>
<div class="weui-uploader__input-box">
    <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple="">
    <img style="margin-top: 10px;" src="/statics/front/images/camera.png" width="45%" alt="">
    <p>Add a picture</p>
</div>

 JS gets image data and preview data

//upload picture
$('#uploaderInput').on('change',function (e) {
    var $this = $(this);

    //image object
    var file = $this.get(0).files[0];
    //file.name The original name of the file
    var maxSize = 2 * 1024 * 1024; ///2M
    if (file.size > maxSize) {
        alert("Upload file must not be larger than 2M");
        return;
    }

    //Convert the image object to a base64-bit format string
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e) {
        post_base64image_str = this.result;

        var imgUrl = window.URL.createObjectURL(file);
        //Get the clicked textbox
        var files = $this.parents('.weui-uploader').find('.weui-uploader__files');
        var html = '<li class="weui-uploader__file">\n' +
          ' <img src="'+imgUrl+'"/>\n<input type="hidden" name="files[]" value="'+post_base64image_str+'"/>\n' +
          '  <i class="weui-icon-cancel"></i>\n' +
          ' </li>'
        files.append(html);
    };
})
//Click the fork to delete the picture
$(document).on('click','.weui-uploader__files .weui-icon-cancel',function () {
    $(this).parents('.weui-uploader__file').remove()
})

The PHP backend converts base64 images into image files

/**
 * [Convert Base64 image to local image and save]
 * @param [Base64] $base64_image_content [Base64 to save]
 * @param [directory] $path [path to save]
 */
function base64_image_content($base64_image_content, $path) {
    // match the format of the image
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
        $type = $result[2]; //Image suffix
        if ($type === 'jpeg') {
            $type = 'jpg';
        }
        $new_file = $path . "/" . date('Ymd', time()) . "/";
        if (!file_exists($new_file)) {
            //Check if the folder exists, if not, create it and give the highest permission
            mkdir($new_file, 0700);
        }
        $new_file = $new_file . md5($base64_image_content) . ".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
            return ltrim($new_file, ".");
        } else {
            return false;
        }
    } else {
        return false;
    }
}

 

Effect screenshot

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325368911&siteId=291194637