Ajax simple implementation of asynchronous file upload methods

Posted by badre on Sun, 15 Dec 2019 16:08:09 +0100

1. Understand FormData object

FormData is a newly added class of Html5, which can simulate form data

Constructor explain
FormData (optional HTMLFormElement form) (optional) an HTML form element that can contain any form of form control, including a file input box

Method

void append(DOMString name, DOMString value)

  • Name form element name
  • Value the value to be passed by the form element
<form name="myForm"  enctype="multipart/form-data">
    <input type="text" name="userName">
    <input type="file" name="img">
    <input type="button" id="btn" value="submit">
</form>

2. Simple implementation with javascript

function upload() {
    var userName = document.myForm.userName.value;
    var img = document.myForm.img.files[0];
    var fm = new FormData();
    fm.append('userName', userName);
    fm.append('img', img);

    var request = new XMLHttpRequest();
    request.open('POST', 'submitform.php');
    request.send(fm);
}

3. Using Ajax to implement

$('#btn').click(function () {
    var userName = document.myForm.userName.value;
    var img = document.myForm.img.files[0];
    
    var fm = new FormData();
    fm.append('userName', userName);
    fm.append('img', img);
    $.ajax(
        {
            url: 'submitform.php',
            type: 'POST',
            data: fm,
            contentType: false, //Disable setting request type
            processData: false, //Disable jquery's processing of DAta of DAta of DAta, which will be processed by default
            //The reason for the prohibition is that FormData has helped us deal with it
            success: function (result) {
                //Test success
                //But you need to have a return value in the backend
                alert(result);
            }
        }
    );
});

4. Ajax file upload.js plug-in realizes Ajax file upload

function upload(){
$.ajaxFileUpload({
        url: 'a.php', //Server side request address for file upload
        secureuri: false, //Generally set to false
        fileElementId: 'file', //id attribute of file upload space  
        dataType: 'HTML', //The return value type is generally set to json
        success: function (data, status)  //Server successfully responded to processing function
        {                
            $("#img1").attr("src", data);
            addI(data);
        },
        error: function (data, status, e)//Server response failure handling function
        {
            alert(e);
        }
    }   
);
} 
  • For PHP, you can use the Files global array to get the file attributes, and the POST global array to get the userName value

Article 1: Personal building wall server

Topics: PHP html5 Javascript JQuery