简体   繁体   中英

jQuery / AJAX - send additional data together with file upload

I am uploading files to the server using jQuery:

 $.ajax({
    url : 'http://www.example.com',
    dataType : 'json',
    cache : false,
    contentType : false,
    processData : false,
    data : formData, // formData is $('#file').prop('files')[0];
    type : 'post',
    success : function(response) {something}
   });

I would like to send additional parameters together with the file. Is it possible? If yes - how?

Thanks!

To send additional parameters, you can just append it to formdata like below:

var formdata=new FormData();
formdata.append('simpleFile', $('#file').get('files')[0]); //use get('files')[0]
formdata.append('someotherparams',someothervalues);//you can append it to formdata with a proper parameter name 

$.ajax({
    url : 'http://www.example.com',
    dataType : 'json',
    cache : false,
    contentType : false,
    processData : false,
    data : formData, //formdata will contain all the other details with a name given to parameters
    type : 'post',
    success : function(response) {something}
});

Try with this,

$( "form" ).on( "submit", function( event ) {
   var formData = $( this ).serialize();
    //$.ajax({}) //remaining code here 
});

您必须使用FormData对象序列化表单,而不仅仅是发送文件。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM