jQuery / AJAX - send additional data together with file upload

前端 未结 3 1858
旧时难觅i
旧时难觅i 2021-01-07 07:34

I am uploading files to the server using jQuery:

 $.ajax({
    url : \'http://www.example.com\',
    dataType : \'json\',
    cache : false,
    contentType          


        
相关标签:
3条回答
  • 2021-01-07 08:19

    You have to serialize the form using the FormData object instead of only sending the file.

    var formData = new FormData($("form")[0]);
    
    0 讨论(0)
  • 2021-01-07 08:23

    Try with this,

    $( "form" ).on( "submit", function( event ) {
       var formData = $( this ).serialize();
        //$.ajax({}) //remaining code here 
    });
    
    0 讨论(0)
  • 2021-01-07 08:32

    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}
    });
    
    0 讨论(0)
提交回复
热议问题