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.
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
})
Thanks to Yashveer Singh, I was able to put all the pieces together. Here's the jQuery/javascript version:
//first, create a Blob object. Assume that variable myCSV has our CSV data as a string
//The Blob constructor requires an array, so place in brackets [].
var myblob = new Blob([myCSV], {type: 'text/csv'});
//Create a new FormData object.
var myFD = new FormData();
//Add our file (the blob) to it.
myFD.append('htmlFormName', myblob, 'someFileName.csv');
//We can also append other fields if necessary.
myFD.append('inputName', 'inputValue');
//If we're using jQuery to send the form...
$.ajax({
url: 'http://remotewebsite.com/formhandler.php',
type: 'POST',
data: myFD,
processData: false, // <-- important!
contentType: false, // <-- important!
success: function(data) {
console.log('Posted successfully.');
}
});