0

I am trying to get the filepath of the selected file. Using the debugger, I see that the file has an property called value which is equal to : "C:\fakepath\filename.txt".

However when I try to access file.value, the filepath is equal to null.
I am using Java 8, Struts 1.2, Jsps, and Chrome Javascript:

function validateFile(file)
{
    filepath = file.value; /*This is null*/
    return true; 
}

Html:

<input type="file" id="theFile[0]" onChange="validateFile(this)"/>
14
  • 3
    You aren't trying to set the value property of anything in that example that I can see. Are you sure that's the right code for the error? Commented May 12, 2016 at 18:08
  • I agree with the above comment. Try changing onChange to validateFile(this) and instead of function validateFile(fileid) use function validateFile(file). Remove the variable declaration for var file also. Commented May 12, 2016 at 18:10
  • @Quentin filepath = file.value when var file = ... was set isn't an attempt to set the value property with filepath? Commented May 12, 2016 at 18:10
  • 1
    @8protons, Cannot set property 'value' means something basically did undefined.value = ... there is no code in the example that does that Commented May 12, 2016 at 18:12
  • @Quentin you are right. The .value is for another part of the code. My apologies. The value of filepath is just null. Commented May 12, 2016 at 18:12

2 Answers 2

2

Try this:

function validateFile(fileinput) {
    var allowed = "pdf,png";
    var filepath=fileinput.value;
    var ext = filepath.substr(filepath.lastIndexOf('.')+1);
    if (filepath = "" || allowed.search(ext) <= -1) {
        fileinput.value='';
        alert('Invalid file type');
        return false;
    }
}
<input type="file" id="inputFile" onChange="validateFile(this)"/>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. However, I just fixed the problem using Jonathan's answer.
I have also +1'd this answer as it would have in fact fixed the issue.
1

I guess it wasn't too much work after all :)

function validateFile(file)
{
    filepath = file.value;
    document.getElementById('result').innerText = filepath;
    return true; 
}
<input type="file" onChange="validateFile(this)"/>
<div id="result">[result will be here]</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.