jQuery Ajax submit a multipart form

摘要: A simple jQuery Ajax example to show you how to submit a multipart form, using Javascript FormData and $.ajax()

A simple jQuery Ajax example to show you how to submit a multipart form, using Javascript FormData and $.ajax()

1. HTML

A HTML form for multiple file uploads and an extra field.

<!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>

2. jQuery.ajax

2.1 Create a Javascript FormData object from a form.

    var form = $('#fileUploadForm')[0];
    var data = new FormData(form);

2.1 processData: false, it prevent jQuery form transforming the data into a query string

	$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        processData: false,  // Important!
        contentType: false,
        cache: false,

2.3 Full example.

$(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");
		// disabled the submit button
        $("#btnSubmit").prop("disabled", true);
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/api/upload/multi",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            success: function (data) {
                $("#result").text(data);
                console.log("SUCCESS : ", data);
                $("#btnSubmit").prop("disabled", false);
            },
            error: function (e) {
                $("#result").text(e.responseText);
                console.log("ERROR : ", e);
                $("#btnSubmit").prop("disabled", false);
        });
    });
});

References

  1. jQuery.ajax()
  2. MDN – Using FormData Objects
  3. Spring Boot file upload example – Ajax and REST

上一篇: Linux How to assign execute permission to a .sh file
下一篇: cURL POST request examples
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号