Search code examples
javascriptjqueryhtmljquery-file-upload

jQuery file upload including variables


Is it possible to use a file upload using jQuery/javascript that would include usable variables? (user selects file)

For example. Could I upload a file (.txt, or .js etc) with the following contents and be able to use the variables?

var cars = ["Saab", "Volvo", "BMW"];

var name = "bob";


Solution

  • Yes you can. Please check below for more in depth.

    Add .txt or any files in formdata

    var formData = new FormData();
    
    var txxtFile = $('#input_file').prop('files')[0];
    formData.append('file',txxtFile);
    

    Append variables in formData

    var carsArray = ["Saab", "Volvo", "BMW"];
    formData.append(cars,  JSON.stringify(carsArray ));
    

    Once you append all values to formData you have to pass formData in ajax request.

    Let me know if it not works.