Get data from file input in JQuery
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
You can try the FileReader API. Do something like this:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
I created a form data object and appended the file:
var form = new FormData();
form.append("video", $("#fileInput")[0].files[0]);
and i got:
------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv
in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla
Html:
<input type="file" name="input-file" id="input-file">
jQuery:
var fileToUpload = $('#input-file').prop('files')[0];
We want to get first element only, because prop('files') returns array.