Hello I want to use pure javascript ajax (no jquery) to append formdata but I don't know how to get data from input file type
function handleForm(e)
{
e.preventDefault();
var username = document.getElementById('username').value;
var email = document.getElementById('email').value;
var data = new FormData();
data.append('username', username);
data.append('email', email);
data.append('file', ?????); ////// How to get data from input file
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test2.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
...
Username: <input type="text" name="username" id="username"><br/>
Email: <input type="text" name="email" id="email"><br/>
Image: <input type="file" name="file" id="myimg"><br/>
<input type="submit">
</form>
The <input type="file" />
HTML element has a files
property (of type FileList
).
Check the length if a file has been selected and if so add the file(s) to the FormData
object
var fileInput = document.getElementById("myimg");
if (fileInput.files.length > 0) {
data.append("file", fileInput.files[0]);
}
For more examples on how to use the FormData
object check this link:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
document.getElementById("file_input_id").files[0]
try
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With