I'm trying to get a local file from a system, I did some searching and came around a way of doing this, when I tried to implement it in my code, I got the error:
Uncaught TypeError: Cannot read property 'type' of undefined
document.getElementById('add-new-cat').addEventListener('click', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files;
if(files.type.match('image.*')) {
var reader = new FileReader();
reader.onload = (function(theFile) {
})(files);
var catIMG = reader.readAsBinaryString(files);
alert(catIMG);
}
}
<input type="file" name="cat_path_orig" id="cat-path-orig">
<button class="btn btn-primary" id="add-new-cat">add</button>
I wouldn't know how to trigger the function with the file included, because I know it's looking for a value in the button that's being clicked
The click
event object doesn't have a files
property. I think you're looking for the files
property on the input type="file"
object:
document.getElementById('add-new-cat').addEventListener('click', handleFileSelect, false);
function handleFileSelect(evt) {
var files = document.getElementById("cat-path-orig").files; // ****
console.log("files.length: " + files.length);
Array.prototype.forEach.call(files, function(file) {
console.log(file.name + ": " + file.type);
});
}
<input type="file" name="cat_path_orig" id="cat-path-orig">
<button class="btn btn-primary" id="add-new-cat">add</button>
A couple of other notes:
You'll want to look at the type
property on each individual file (see the snippet above). In your example, there will be only one (because there's no multiple
attribute on the input type="file"
), so you could just use files[0]
rather than the loop I've used above.
Your use of readAsBinaryString
is also incorrect; here's an answer with a correct example.