Text Content and FileUpload with AJAX

后端 未结 2 1579
别那么骄傲
别那么骄傲 2021-01-13 08:53

I am writting a client database system for my company. Not much fancy stuff, but it does what it should. Now that all the basic \"text\" stuff is done I want to add some fil

相关标签:
2条回答
  • 2021-01-13 09:15

    Use jquery malsup form plugin to send files using AJAX

    https://github.com/malsup/form

    0 讨论(0)
  • 2021-01-13 09:31

    For ajax uploads you need to use xmlHttpRequest which is already available in the jQuery.ajax() method, but with use of FormData.

    If you are not targeting IE legacy versions, like 7,8 you can use FormData. One thing to be noticed that you have to set contentType, processData to false.

    See the example below:

    var name = $('#name').val();
    var somethingElse = $('#somethingElse').val();
    var fd = new FormData();
    var dataArr = {
      name: name,
      somethingElse: somethingElse,
      file : fd.append('file', $('#fileUpload').get(0).files[0]) // put the file here
    };
    
    MYELEMENT.click(function(e) {
      e.preventDefault();
      $.ajax({
        url: "PATH/logic/logic_update_client_allg.php",
        type: "POST",
        data: dataArr, //<----post here the files and other values
        processData: false,  // tell jQuery not to process the data
        contentType: false   // tell jQuery not to set contentType
        success: function(dataArr) {
          // works
        },
        error: function() {
          // doesnt work
        }
      });
    });
    
    0 讨论(0)
提交回复
热议问题