简体   繁体   English

jQuery / AJAX - 将附加数据与文件上传一起发送

[英]jQuery / AJAX - send additional data together with file upload

I am uploading files to the server using jQuery:我正在使用 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:要发送其他参数,您只需将其附加到formdata如下所示:

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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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