How to use FormData for AJAX file upload?

后端 未结 9 1357
不思量自难忘°
不思量自难忘° 2020-11-21 06:13

This is my HTML which I\'m generating dynamically using drag and drop functionality.

相关标签:
9条回答
  • 2020-11-21 06:42

    For correct form data usage you need to do 2 steps.

    Preparations

    You can give your whole form to FormData() for processing

    var form = $('form')[0]; // You need to use standard javascript object here
    var formData = new FormData(form);
    

    or specify exact data for FormData()

    var formData = new FormData();
    formData.append('section', 'general');
    formData.append('action', 'previewImg');
    // Attach file
    formData.append('image', $('input[type=file]')[0].files[0]); 
    

    Sending form

    Ajax request with jquery will looks like this:

    $.ajax({
        url: 'Your url here',
        data: formData,
        type: 'POST',
        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
        processData: false, // NEEDED, DON'T OMIT THIS
        // ... Other options like success and etc
    });
    

    After this it will send ajax request like you submit regular form with enctype="multipart/form-data"

    Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.

    Note: contentType: false only available from jQuery 1.6 onwards

    0 讨论(0)
  • 2020-11-21 06:46

    Actually The documentation shows that you can use XMLHttpRequest().send() to simply send multiform data in case jquery sucks

    0 讨论(0)
  • 2020-11-21 06:47
    <form id="upload_form" enctype="multipart/form-data">
    

    jQuery with CodeIgniter file upload:

    var formData = new FormData($('#upload_form')[0]);
    
    formData.append('tax_file', $('input[type=file]')[0].files[0]);
    
    $.ajax({
        type: "POST",
        url: base_url + "member/upload/",
        data: formData,
        //use contentType, processData for sure.
        contentType: false,
        processData: false,
        beforeSend: function() {
            $('.modal .ajax_data').prepend('<img src="' +
                base_url +
                '"asset/images/ajax-loader.gif" />');
            //$(".modal .ajax_data").html("<pre>Hold on...</pre>");
            $(".modal").modal("show");
        },
        success: function(msg) {
            $(".modal .ajax_data").html("<pre>" + msg +
                "</pre>");
            $('#close').hide();
        },
        error: function() {
            $(".modal .ajax_data").html(
                "<pre>Sorry! Couldn't process your request.</pre>"
            ); // 
            $('#done').hide();
        }
    });
    

    you can use.

    var form = $('form')[0]; 
    var formData = new FormData(form);     
    formData.append('tax_file', $('input[type=file]')[0].files[0]);
    

    or

    var formData = new FormData($('#upload_form')[0]);
    formData.append('tax_file', $('input[type=file]')[0].files[0]); 
    

    Both will work.

    0 讨论(0)
  • 2020-11-21 06:47
    View:
    <label class="btn btn-info btn-file">
    Import <input type="file" style="display: none;">
    </label>
    <Script>
    $(document).ready(function () {
                    $(document).on('change', ':file', function () {
                        var fileUpload = $(this).get(0);
                        var files = fileUpload.files;
                        var bid = 0;
                        if (files.length != 0) {
                            var data = new FormData();
                            for (var i = 0; i < files.length ; i++) {
                                data.append(files[i].name, files[i]);
                            }
                            $.ajax({
                                xhr: function () {
                                    var xhr = $.ajaxSettings.xhr();
                                    xhr.upload.onprogress = function (e) {
                                        console.log(Math.floor(e.loaded / e.total * 100) + '%');
                                    };
                                    return xhr;
                                },
                                contentType: false,
                                processData: false,
                                type: 'POST',
                                data: data,
                                url: '/ControllerX/' + bid,
                                success: function (response) {
                                    location.href = 'xxx/Index/';
                                }
                            });
                        }
                    });
                });
    </Script>
    Controller:
    [HttpPost]
            public ActionResult ControllerX(string id)
            {
                var files = Request.Form.Files;
    ...
    
    0 讨论(0)
  • 2020-11-21 06:48

    Good morning.

    I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.

    <input type="file" name="files[]" multiple>
    

    I did not make any modification on FormData.

    0 讨论(0)
  • 2020-11-21 06:56
    $(document).ready(function () {
        $(".submit_btn").click(function (event) {
            event.preventDefault();
            var form = $('#fileUploadForm')[0];
            var data = new FormData(form);
            data.append("CustomField", "This is some extra data, testing");
            $("#btnSubmit").prop("disabled", true);
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: "upload.php",
                data: data,
                processData: false,
                contentType: false,
                cache: false,
                timeout: 600000,
                success: function (data) {
                    console.log();
                },
            });
        });
    });
    
    0 讨论(0)
提交回复
热议问题