I am wondering how can I get the content of the file. I have the following HTML :
<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<input type="text" id = "textExtrafield" name="extraField"/><br/><br/>
<input type="file" id = "fileOne" name="files"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<button type = "button" onclick="submitFileTest()">Submit Button April 13 </button>
</form>
The line var fileInputElement = document.getElementById("fileOne"); gets me the name of the file. However, if I want to get the content of the file, what approach do I need to follow? My main goal is to append the content of the file like this formData.append("firstfile", fileInputElement); and send the formData object via JSON.
function submitFileTest() {
var textField = $('#textExtrafield').val();
var formData = new FormData();
formData.append("textField", textField);
//alert(formData);
var fileInputElement = document.getElementById("fileOne");
alert(fileInputElement.value);
// HTML file input, chosen by user
formData.append("firstfile", fileInputElement);
alert(formData);
}
Thanks Got it. I did the following inside the submitFileTest() function :
And I saw the alert for formData in the form of [object FormData].
If I have to send this [object FormData] via ajax to a PHP file. How can I retrieve it? I would basically like to have something like a JSON object so that I could send it to my Java webservice which will accept the name and value pairs.
var textField = $uabjquery('#textExtrafield').val();
var formData = new FormData();
formData.append("textField", textField);
var fileInputElement = document.getElementById("fileOne");
alert(fileInputElement.value);
formData.append('firstFile', fileInputElement.files[0]);
// HTML file input, chosen by user
//formData.append("firstfile", fileInputElement);
alert(formData);
Also does this [object FormData] contains one file if I select one file & two files if I select two files from two different inputs?
With the $_FILES variable; also see the section about handling file uploads. Note that a FormData object is not JSON though, it’s just, well, form data; and unlike JSON it can also contain binary data such as files.
It can contain as many files as you .append() to it.
BTW, you’ll get mach better information if you console.log() your data instead of alert()ing it, as the latter coerces everything to a string, and something like [object FormData] isn’t particularly useful for debugging.
Upon adding console log in IE, I saw the following : I don’t quite understand this. Does this looks correct and would I be able to retrieve files in PHP with this information?
These are the methods on your FormData object… OK in this case this isn’t particularly helpful indeed. ^^ In modern browsers you can log it’s entries like this though:
console.log(formData.entries())
// Or short version using the spread syntax
console.log(...formData)