jQuery: get the file name selected from <input type="file" />
This code should work in IE (don't even test it in Firefox), but it doesn't. What I want is to display the name of the attached file. Any help?
<html>
<head>
<title>example</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$("#attach").after("<input id='fakeAttach' type='button' value='attach a file' />");
$("#fakeAttach").click(function() {
$("#attach").click();
$("#maxSize").after("<div id='temporary'><span id='attachedFile'></span><input id='remove' type='button' value='remove' /></div>");
$('#attach').change(function(){
$("#fakeAttach").attr("disabled","disabled");
$("#attachedFile").html($(this).val());
});
$("#remove").click(function(e){
e.preventDefault();
$("#attach").replaceWith($("#attach").clone());
$("#fakeAttach").attr("disabled","");
$("#temporary").remove();
});
})
});
</script>
</head>
<body>
<input id="attach" type="file" /><span id="maxSize">(less than 1MB)</span>
</body>
</html>
Solution 1:
It is just such simple as writing:
$('input[type=file]').val()
Anyway, I suggest using name or ID attribute to select your input. And with event, it should look like this:
$('input[type=file]').change(function(e){
$in=$(this);
$in.next().html($in.val());
});
Solution 2:
The simplest way is to simply use the following line of jquery
, using this you don't get the /fakepath
nonsense, you straight up get the file that was uploaded:
$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id
Some other useful commands are:
To get the name of the file:
$('input[type=file]')[0].files[0].name; // This gets the file name
To get the type of the file:
If I were to upload a PNG, it would return image/png
$("#imgUpload")[0].files[0].type
To get the size (in bytes) of the file:
$("#imgUpload")[0].files[0].size
Also you don't have to use these commands on('change'
, you can get the values at any time, for instance you may have a file upload and when the user clicks upload
, you simply use the commands I listed.