This is the 21st day of my participation in the August Text Challenge.More challenges in August

Preface:

How to upload a file with a progress bar in jQuery

Effect requirements:

In the input box of file type, select the input file and click the submit button below to display the file uploading progress bar. After the image uploading is completed, the image uploaded to the back end will be displayed.

Structure construction:

<form> <input type="file" name="avatar" class="fileIpt"> </form> <! < span style="display: none; max="100" value="5"></progress> <! - display pictures - > < img width = "500" id = "PIC" SRC = "" Alt =" ">Copy the code

Style section:

    <style>
        * {
            margin: 0;
            padding: 0;
        }
        body {
            width: 100%;
            height: 100%;
            position: fixed;
            background-image: url(./sky.jpg);
        }
        form {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);

        }
        .fileIpt{
            display: none;
        }
    </style>
Copy the code

Technical introduction:

This implementation uses jQuery, Ajax, and FormData to collect data

The introduction of the jQuery

< script SRC = "jquery - 1.12.4. Js" > < / script >Copy the code

Define jQ objects for use below

var form = $("form");
var progress = $("progress");
var pic = $("#pic");
var chanceFile = $(".chanceFile");
var fileIpt = $(".fileIpt");
Copy the code

Text input box click triggers the click event of the file input box:

chanceFile.on('click',function(){
    fileIpt.click(); 
})
Copy the code

The submit event of the button is decomposed into the following steps:

form.on("submit", function (e) { e.preventDefault(); Var fd = new FormData(this); var files=fileIpt[0].files; console.log(files); chanceFile[0].value=fileIpt.val().split("\\")[2]; // jQ ajax method $. Ajax ({type: "POST", url: "http://xxx/upload/avatar", // image upload url, you can set it according to the situation, data: fd, contentType: False, processData: false, XHR: function () {var XHR = new XMLHttpRequest(); Upload. Onprogress event ==> Will be triggered when the upload progress changes // Note: The event needs to be registered before SEND, Xhr.upload. onprogress = function (e) {// Use the event object e to get the total size of the uploaded file and the current size of the uploaded file // set the current upload size to the value assigned to the progress bar. // console.log(e); // Display progress bar progress.show(); progress.attr("max", e.total); progress.attr("value", e.loaded); } return XHR; }, success: function (info) { // console.log(info); Parse () pic.attr(" SRC ", "http://www.xxx" + info.url); // This is the address name of the server to upload the image to}})Copy the code

Postscript:

The effect is achieved, we quickly try ~