ajax方式提交file类型的form

  • html的代码:
    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>jQuery Ajax submit Multipart form</h1>
    
    <form method="POST" enctype="multipart/form-data" id="fileUploadForm">
        <input type="text" name="extraField"/><br/><br/>
        <input type="file" name="files"/><br/><br/>
        <input type="file" name="files"/><br/><br/>
        <input type="submit" value="Submit" id="btnSubmit"/>
    </form>
    
    <h1>Ajax Post Result</h1>
    <span id="result"></span>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
    </body>
    </html>

     

  • jQuery代码:
    $(document).ready(function () {
        $("#btnSubmit").click(function (event) {
    
            //stop submit the form, we will post it manually.
            event.preventDefault();
    
            // Get form
            var form = $('#fileUploadForm')[0];
    
            // Create an FormData object
            var data = new FormData(form);
    
            // If you want to add an extra field for the FormData
            data.append("CustomField", "This is some extra data, testing");
    
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: "/api/upload/multi",
                data: data,
                processData: false, //Important, it prevent jQuery form transforming the data into a query string
                contentType: false,
                cache: false,
                success: function (data) { 
                    console.log("SUCCESS : ", data);//your logic
    
                },
                error: function (e) {
                    console.log("ERROR : ", e); //your logic
                }
            });
    
        });
    
    });

     

posted @ 2017-08-09 11:46  java后端领域  阅读(1241)  评论(0)    收藏  举报