Accessing value of javascript file input variable - javascript

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)"/>

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)"/>

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>

Related

How to not open File upload when parameters are not meet javascript

How to not open the file upload box when input mytextField is null.
<input type="text" id="mytextField">
<input type="file" multiple id="myFileUpload">
<script>
document.getElementById("myFileUpload").addEventListener("click", function () {
var myTextF = document.getElementById("mytextField");
if(myTextF = null || myTextF == ''){
//will not open the file upload
} else {
//let the file upload open
}
});
</script>
You can disable the upload button when textarea is empty and enable it when textarea contains text.
<input type="text" onkeyup="checkField()" id="mytextField">
<input type="file" multiple id="myFileUpload" disabled="disabled">
script:
function checkField(){
var myTextF = document.getElementById("mytextField");
if(myTextF.value.trim() != ""){
document.getElementById("myFileUpload").disabled = false;
}
}
Used the trim() function to prevent empty whitespace texts.
Here you are assigning myTextF to the element, rather than the innerText.
Try with var myTextF = document.getElementById("myTextF").innerText;
If something doesn't work, you could always try to log the output to the console.
In this case, because you are assigning the element, that resolves as TRUE, and it will always try to open the file.
document.getElementById("myFileUpload").addEventListener("click", function () {
var myTextF = document.getElementById("mytextField");
if(myTextF = null || myTextF == ''){
//will not open the file upload
console.log("I should not open file")
} else {
//let the file upload open
console.log("I should open the file")
}
});
" I should open the file"

Javascript function parameter does not work

In my html form I have 4 file input fields.
<input type="file" id="one" name="Title_image1" onchange="check_extension(one)"/>
<input type="file" id="one2" name="Title_image2" onchange="check_extension(one3)"/>
<input type="file" id="one3" name="Title_image3" onchange="check_extension(one4)"/>
<input type="file" id="one4" name="Title_image4" onchange="check_extension(one5)"/>
I want to check file extension on inputs using javascript.
My function
function check_extension($field_id)
{
var allowed = {'jpg': 1, 'png': 1};
var fileinput = document.getElementById("$field_id");
var y = fileinput.value.split(".");
var ext = y[(y.length) - 1];
ext = ext.toLowerCase();
if (allowed[ext]) {
document.chooseF.confirm.disabled = false;
return true;
} else {
alert("This is an unsupported file type. Supported files are: jpg,png");
document.chooseF.confirm.disabled = true;
return false;
}
}
I am using the same function for all the input fields with fieldid as parameter, but it does not work.
onchange="check_extension(one)"
Here one is the Node with the id "one", one is not the string "one"
document.getElementById("$field_id");
Even if $field_id is the id "one", "$field_id" is a different string
So getElementById("$field_id") will give you the node with id "$field_id", not the node with id "one".
Fixes
onchange="check_extension('one')"
and
document.getElementById($field_id)
Also I discourage naming string variables with a leading $
change this:
<input type="file" id="one" name="Title_image1" onchange="check_extension(one)"/>
like so:
<input type="file" id="one" name="Title_image1" onchange="check_extension('one')"/>
Then change this:
function check_extension($field_id)
{
var allowed = {'jpg': 1, 'png': 1};
var fileinput = document.getElementById("$field_id");
....
like so:
function check_extension(field_id)
{
var allowed = {'jpg': 1, 'png': 1};
var fileinput = document.getElementById(field_id);
...

How to determining if a file has been selected in JavaScript?

I'm using JavaScript to validate an uploading form, one of the conditions is to check if any file has been selected. I thought this would be simple, but I can't get it to work. Is this code invalid? The var file works with other conditions so it's not that
var file = document.getElementById('file');
if(file.value =="") {
alert("no file selected")
return false;
}
<input name="uploaded" type="file" id="file" />
You can use the following example:
var fileInput = document.getElementById('file');
fileInput.onchange = function () {
var input = this.files[0];
if (input) {
//process input.
} else {
alert("Please select a file.");
}
};
Hope this helps.

File type validation!! for generated input file tag elements

JSP:
----
<div ID="items">
input id="file5" type="file" path="files" name="files" size="40" /> Other documents
</div>
Javascript:
-----------
<script type="text/javascript">
var items=1;
function AddItem() {
var div=document.getElementById("items");
var button=document.getElementById("add");
items++;
newitem="";
newitem+="<input type=\"file\" path=\"files\" name=\"files\"";// + items;
newitem+="\"id=file"+items;
newitem+="\" size=\"40\"> Other documents";
newitem+=" <input type=\"button\" class=\"button\" id=\"delButton"+items;
newitem+="\" value=\"\" name=\"button"+items;
newitem+="\" onclick=deletethisRow("+items+")>";
newnode=document.createElement("div");
newnode.setAttribute("id","child"+items);
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
}
function deletethisRow(obj){
var fileElement=document.getElementById("file"+obj);
var buttonElement=document.getElementById("delButton"+obj);
var childDivName="child"+obj;
if (buttonElement) {
var child = document.getElementById(childDivName);
var parent = document.getElementById("items");
parent.removeChild(child);
}
}
</script>
---
Above is the JSP code as well as JavaScript snippets.. I'm trying to validate the input files....
I want to allow only jpg,png,pdf,doc,docx file types to be upload??
Any thoughts on how to achieve this?
Thanks and regards,
Satish Krishnamurthy
You can change your input tag:
<input type="file" name="pic" id="pic" accept=".someext, image/gif, image/jpeg" />
But please don't rely on client-side validation. Check it server-side or people can disable the client-side checks and upload even executable scripts.
function Checkfilesextension()
{
var fileToupload = document.getElementById('elementId');
var fileName = fileToupload .value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
ext.toLowerCase
if(ext =="GIF" || other extension) // add other extensions
{
return true;
}
else
{
alert("Upload only the allowed files");
return false;
}
}
This would check for the extension of the files....have not tested the code though

Javascript validate filename before upload

I simply want to validate the filename of the image being uploaded to ensure that it does not have spaces or unusual characters.
This is my latest attempt from searching around, still no luck. Could it be something to do with the path of the file? is it taking this or just the file name into account?
I have this and a check of the extention working server side with php, but I would like a prompt to the user before submitting.
At this point in time im getting the alert pop up even whether i use a file name it should accept or one that it should reject.
JavaScript
function validate(elem){
var alphaExp = /^[a-zA-Z_-]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert("File name not suitable");
elem.focus();
return false;
}
}
HTML
<label for="file">Filename:</label>
<input type="file" name="filename" id="filename" onchange="validate(this)" />
<p><input type="submit" name="submit" class="submit" value="Submit" />
</form>
You will need to use a much more complex regular expression for this, because the elem.value you are checking won't be something like image123.jpg but more something like C:\fakepath\randomfolder\some other folder\image123.jpg
You might want to check into this : http://www.codeproject.com/Tips/216238/Regular-Expression-to-validate-file-path-and-exten
The exemple you'll find on this page is mostly for documents, not images, but you can twist it a bit to fit your needs like this :
^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(png|gif|jpg|jpeg)$
you can use this function too....
<script type="text/javascript">
function getNameFromPath(strFilepath) {
var objRE = new RegExp(/([^\/\\]+)$/);
var strName = objRE.exec(strFilepath);
if (strName == null) {
return null;
}
else {
return strName[0];
}
}
</script>
and
<script language="javascript">
function Checkfiles() {
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc") {
return true;
} else {
alert("Upload Gif or Jpg images only");
fup.focus();
return false;
}
}
</script>
it is very very simple with test function
function validate(form){
if (/\s/.test(form.elements.file.value)) {
alert(' filename contains spaces. Please rename the file.');
return false;
}
return true;
}
<html>
<body>
<form onsubmit="return validate(this);">
<input type="file" name="file" value="" >
<input type="Submit" value="Submit" >
</form>
</body>
</html>
Source https://codehurdles.blogspot.in/2017/11/javascript-validate-filename-before.html

Categories

Resources