Text Content and FileUpload with AJAX

2020-03-20 17:21发布

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 filemanagement into it.

I have several forms which get send to the backend with ajax and then written into the db in the model.

Some of these forms are planned to have a document file upload.

Is there a way to handle normal value submits and a file submit with AJAX ?

Let me give you a FORM example:

<form action="SOMEPATH/LOGIC_FILE.php" action="POST" enctype= multipart/form-data>
  <label for="name">
   <input type="text" id="name" name="name" />
  </label>
  <label for="somethingElse">
   <input type="text" id="somethingElse" name="somethingElse" />
  </label>
  <label for="fileUpload">
    <input type="file" />
  </label>
</form>

AJAX example:

var name = $('#name').val();
var somethingElse = $('#somethingElse').val();

var dataArr = { 'name':name, 'somethingElse':somethingElse};
MYELEMENT.click(function(e){
e.preventEventDefault();
$.ajax({
            url: "PATH/logic/logic_update_client_allg.php",
            type: "POST",
            data: allgArray,
            success: function(dataArr){
                // works
            },
            error: function(){
                // doesnt work
            }
        });
}

Thats how I handle my INPUT VALUE submit

How can I proceed to also upload a file with this form

Thank you

2条回答
forever°为你锁心
2楼-- · 2020-03-20 18:01

Use jquery malsup form plugin to send files using AJAX

https://github.com/malsup/form

查看更多
Explosion°爆炸
3楼-- · 2020-03-20 18:03

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
    }
  });
});
查看更多
登录 后发表回答