Search code examples
phpjqueryfile-uploadforums

Using PHP or jQuery to submit a dynamically generated file


I am trying to interact with the "API" at another company. Their API is actually a file upload form which asks for a CSV file. It's a standard HTML form with an element like so:

<input type="file" id="inputFileUploadFile" name="UploadFile">

I have a page where a user can view a set of table data. I am looking for a way to have a one-button solution where the user can look at the table data and submit it as a file to this so-called API.

Generating the data in CSV format is easy enough. The question, specifically, is how do I then get that data into the form element and submit it?

I can either use jQuery to manipulate and submit a hidden HTML form, or I can use PHP to submit the form directly. An answer in either format works.


Solution

  • One approach is to use FormData Class . Below find below a sample code . You need to call this inside the function when you are calling the post on button click etc.

            --- add  enctype to form tag----  
           <form id="upload_form" enctype="multipart/form-data">
    
            -- on submit create a new object assing key value pairs and post it .
    
            var formData = new FormData($('#upload_form')[0]);
    
            formData.append('key1', 'val1');
            formData.append('key2', 'val2');
            // Main magic with files here
            formData.append('image', $('input[type=file]')[0].files[0]); 
    
    
            $.ajax({
                url: 'Your url here',
                data: formData,
                type: 'POST',
                // THIS MUST BE DONE FOR FILE UPLOADING
                contentType: false,
                processData: false,
                // ... Other options like success and etc
            })