如何使用FormData进行ajax文件上传?

时间:2022-08-25 16:25:57

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

这是我使用拖放功能动态生成的html。

<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
    <div id="legend" class="">
        <legend class="">file demoe 1</legend>
        <div id="alert-message" class="alert hidden"></div>
    </div>

    <div class="control-group">
        <!-- Text input-->
        <label class="control-label" for="input01">Text input</label>
        <div class="controls">
            <input type="text" placeholder="placeholder" class="input-xlarge" name="name">
            <p class="help-block" style="display:none;">text_input</p>
        </div>
        <div class="control-group">  </div>
        <label class="control-label">File Button</label>

        <!-- File Upload --> 
        <div class="controls">
            <input class="input-file" id="fileInput" type="file" name="file">
        </div>
    </div>
    <div class="control-group">    

        <!-- Button --> 
        <div class="controls">
            <button class="btn btn-success">Button</button>
        </div>
    </div>
</fieldset>
</form> 

this is my js code...

这是我的js代码…

<script>
    $('.wpc_contact').submit(function(event){
        var formname = $('.wpc_contact').attr('name');
        var form = $('.wpc_contact').serialize();               
        var FormData = new FormData($(form)[1]);

        $.ajax({
            url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
            data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
            type : 'POST',
            processData: false,
            contentType: false,
            success : function(data){
            alert(data); 
            }
        });
   }

6 个解决方案

#1


277  

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

对于正确的表单数据使用,您需要执行两个步骤。

Preparations

准备工作

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

您可以将整个表单提交到FormData()进行处理。

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

or specify exact data for FormData()

或为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:

使用jquery的Ajax请求如下:

$.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"

在此之后,它将发送ajax请求,就像您提交带有enctype="multipart/form-data"的规则表单一样

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

更新:此请求不能在没有类型的情况下工作:“POST”在选项中,因为所有文件都必须通过POST请求发送。

Note: contentType: false only available from jQuery 1.6 onwards

注意:contentType: false只能从jQuery 1.6开始。

#2


23  

I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add

我不能在上面加上评论,因为我没有足够的名气,但是上面的答案对我来说几乎是完美的,除了我必须补充。

type: "POST"

类型:“文章”

to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:

. ajax调用。我苦苦思索了几分钟,想弄明白我做错了什么,这就是它所需要的,而且能奏效。这是整个片段:

Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.

完全归功于我的答案,这只是一个小小的调整。这只是为了防止其他人被卡住,看不到明显的东西。

  $.ajax({
    url: 'Your url here',
    data: formData,
    type: "POST", //ADDED THIS LINE
    // THIS MUST BE DONE FOR FILE UPLOADING
    contentType: false,
    processData: false,
    // ... Other options like success and etc
})

#3


13  

<form id="upload_form" enctype="multipart/form-data">

jQuery with CodeIgniter file upload:

使用CodeIgniter文件上传的jQuery:

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.

都工作。

#4


1  

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

实际上,文档显示您可以使用XMLHttpRequest().send()来简单地发送多个表单数据,以防jquery糟糕。

#5


0  

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;
...

#6


0  

$('#form-withdraw').submit(function(event) {

    //prevent the form from submitting by default
    event.preventDefault();



    var formData = new FormData($(this)[0]);

    $.ajax({
        url: 'function/ajax/topup.php',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) {
          if(returndata == 'success')
          {
            swal({
              title: "Great",
              text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
              type: "success",
              showCancelButton: false,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "OK",
              closeOnConfirm: false
            },
            function(){
              window.location.href = '/transaction.php';
            });
          }

          else if(returndata == 'Offline')
          {
              sweetAlert("Offline", "Please use other payment method", "error");
          }
        }
    });



}); 

#1


277  

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

对于正确的表单数据使用,您需要执行两个步骤。

Preparations

准备工作

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

您可以将整个表单提交到FormData()进行处理。

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

or specify exact data for FormData()

或为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:

使用jquery的Ajax请求如下:

$.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"

在此之后,它将发送ajax请求,就像您提交带有enctype="multipart/form-data"的规则表单一样

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

更新:此请求不能在没有类型的情况下工作:“POST”在选项中,因为所有文件都必须通过POST请求发送。

Note: contentType: false only available from jQuery 1.6 onwards

注意:contentType: false只能从jQuery 1.6开始。

#2


23  

I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add

我不能在上面加上评论,因为我没有足够的名气,但是上面的答案对我来说几乎是完美的,除了我必须补充。

type: "POST"

类型:“文章”

to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:

. ajax调用。我苦苦思索了几分钟,想弄明白我做错了什么,这就是它所需要的,而且能奏效。这是整个片段:

Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.

完全归功于我的答案,这只是一个小小的调整。这只是为了防止其他人被卡住,看不到明显的东西。

  $.ajax({
    url: 'Your url here',
    data: formData,
    type: "POST", //ADDED THIS LINE
    // THIS MUST BE DONE FOR FILE UPLOADING
    contentType: false,
    processData: false,
    // ... Other options like success and etc
})

#3


13  

<form id="upload_form" enctype="multipart/form-data">

jQuery with CodeIgniter file upload:

使用CodeIgniter文件上传的jQuery:

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.

都工作。

#4


1  

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

实际上,文档显示您可以使用XMLHttpRequest().send()来简单地发送多个表单数据,以防jquery糟糕。

#5


0  

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;
...

#6


0  

$('#form-withdraw').submit(function(event) {

    //prevent the form from submitting by default
    event.preventDefault();



    var formData = new FormData($(this)[0]);

    $.ajax({
        url: 'function/ajax/topup.php',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) {
          if(returndata == 'success')
          {
            swal({
              title: "Great",
              text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
              type: "success",
              showCancelButton: false,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "OK",
              closeOnConfirm: false
            },
            function(){
              window.location.href = '/transaction.php';
            });
          }

          else if(returndata == 'Offline')
          {
              sweetAlert("Offline", "Please use other payment method", "error");
          }
        }
    });



});