Carmela
Carmela

Reputation: 687

how to retrieve filename from input type=file value

I have this function for validating image files uploaded through this:

<input accept="image/*" type="file" name="temp_picture" id="temp_picture">
//onchange
validate($(this).attr('name')); //I had to use the attribute name in some other function

And then I have this checker in a function if it is a valid jpeg/jpg file

function validate(pictureId){
    var fileExtension = document.getElementById(pictureId).value.split('.').pop().toLowerCase();
    //etc
}

The problem is, I could not get the image filename from value. The code below returns an empty string:

console.log(document.getElementById(pictureId).value);

Upvotes: 0

Views: 2529

Answers (6)

Professor Abronsius
Professor Abronsius

Reputation: 33823

You could try using the "filelist" api, like this:

var file = document.getElementById( 'temp_picture' ).files[0];
alert(file.name);

https://developer.mozilla.org/en-US/docs/Web/API/FileList


HTML
----
    <form id='bob'>
        <input accept="image/*" type="file" name="temp_picture" id="temp_picture" multiple>
        <div id='output'></div>
    </form>


Javascript
----------
        function getvalues(){

            var output=document.getElementById('output');
            var input=document.getElementById('temp_picture');

            input.onchange=function(e){
                var files=input.files;
                for( var i=0; i < files.length; i++ ) {
                    createNode( 'pre',{ innerHTML:'Name='+files[i].name+'<br />Size='+files[i].size+'<br />Type='+files[i].type, style:'margin:3em' }, output );
                }
            }
        }
/*
There is a function here called 'createNode' - basically it uses document.createElement but also adds attributes to newly generated nodes. I have not included it for reasons of brevity.
*/

 window.onload=getvalues;

Upvotes: 1

ameya rote
ameya rote

Reputation: 1114

Check out below code for your help:

It check s the file size and file type

<!DOCTYPE html>
<html>
<body>
<input type="file" name="image_file" id="image_file" onchange="fileSelected();">`
`<script>
var iMaxFilesize = 1048576; // 1MB
function fileSelected()
{
// get selected file element
var oFile = document.getElementById('image_file').files[0];
// filter for image files
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! rFilter.test(oFile.type)) {
    alert("Not a proper file format");
    return;
}
// little test for filesize
if (oFile.size > iMaxFilesize) {
    alert("File size exceeded");
    return;
}
alert("success = "+oFile.name);
}
</script>
</body>
</html>

Upvotes: 1

user3117575
user3117575

Reputation:

Take a look at how I did it, it takes into consideration of the \fakepath\, it also fetches both the extension and the filename:

document.getElementById("temp_picture").onchange=function(){
  var removeFakePath = this.value.split("\\"); // For the browser that add a fake path
  var getFileWithExt = removeFakePath[removeFakePath.length - 1];
  var splitExtension = getFileWithExt.split(".");
  var filename = splitExtension[0];
  var extension = splitExtension[1];
    alert("Filename:" + filename + "\n\rExtension:" + extension);
};

Fiddle Example

Upvotes: 1

Pranav
Pranav

Reputation: 666

You have given your id wrong in the function..Thats the main problem for the error message.

I am attaching a demo here satisfying your requirements.Do check.

http://plnkr.co/edit/QlGMSL6xJulxBSPBbB1f?p=preview

Upvotes: 1

rEnJiTH
rEnJiTH

Reputation: 26

write the following function on the click event of button or something you are going to use

function checkvalid()
{
   var file_name = document.getElementById("temp_picture").value;
   var file_extn=file_name.split('.').pop().toLowerCase();
   switch(file_extn) {
        //if .jpg/.gif/.png do something
        case 'jpg': case 'gif': case 'png':

            /* handle */
            break;
        //if .zip/.rar do something else
        case 'zip': case 'rar':
            /* handle */`enter code here`
            break;

        //if .pdf do something else
        case 'pdf':
            /* handle */
            break;
    }   
}

Upvotes: 1

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201866

Your code uses the undefined identifier pictureId. Use the string '#temp_picture' instead.

If you actually had var pictureId = '#temp_picture' but forgot to include it in the code you posted, the odds are that the code is being executed before the user made any selection. It works if you execute the code e.g. in an onchange even handler.

Note that the name returned is usually not the true pathname of the file but could be e.g. C:\fakepath\foo.png. This is a security measure, intended to prevent pages from inspecting the file system of the user’s computer. Here it does not matter, since you apparently want to look just at the last few characters of the name.

Upvotes: 1

Related Questions