Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

jquery - How to get the fileName in javascript from input file tag in IE browser

I have done this in jQuery, to get filename from input file tag, With jQuery it works perfectly.

//jQuery('input[type=file]').on('change', prepareUpload);

document.getElementsByTagName('input[type=file]').addEventListener('change',prepareUpload1,true);

/*
//this works in jQuery 

function prepareUpload(event)
{
  var files = event.target.files;
  var fileName = files [0].name
alert(fileName);
}

*/

/****Check it here ****/

// it does not work in javascript 


function prepareUpload1(event)
{
  var files = event.target.files;
  var fileName = files [0].name
alert("fileName 2 : "+fileName);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the problem to be in getElementsByTagName method, you use this when you have a group of elements with the same tag name.

Try this code below, it works

//HTML
<input id="inp" type="file" />


// JavaScript
document.getElementById('inp').addEventListener('change',prepareUpload,false);

function prepareUpload(event)
{
  var files = event.target.files;
  var fileName = files[0].name;
  alert(fileName);
}

Below is the code if you want to do it for more than one element

<body>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>

<script>
var inputArray = document.getElementsByClassName('input');

for(var i = 0; i < inputArray.length; i++){
    inputArray[i].addEventListener('change',prepareUpload,false);
};

function prepareUpload(event)
{
    var files = event.target.files;
    var fileName = files[0].name;
    alert(fileName);
}
</script>
</body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...