How to use FormData for AJAX file upload?

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

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

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

    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:

    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
    })
    
    0 讨论(0)
  • 2020-11-21 06:58
    $('#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");
              }
            }
        });
    
    
    
    }); 
    
    0 讨论(0)
  • 2020-11-21 07:01

    Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").

    $.ajax( {
          url: "http://yourlocationtopost/",
          type: 'POST',
          data: new FormData(document.getElementById("yourFormElementID")),
          processData: false,
          contentType: false
        } ).done(function(d) {
               console.log('done');
        });
    
    0 讨论(0)
提交回复
热议问题