I am checking the file size and extension of a file before it is uploaded, and (for the most part) the code is running correctly. However, I am unable to remove the disabled attribute from the submit button if the file has the correct extension and is under 2MB. I feel as if there is something minor I am not seeing or forgetting. I would appreciate any help or tips.
Thanks,
-Kyle
Here is my code:
<p>Select a logo to upload</p>
<input type="file" id="uploadFile" class="upload" name="upfile"><br>
<input type="submit" id="uploadSubmit" value="Upload Image" disabled="disabled">
document.getElementById("uploadFile").addEventListener("change", checkFile, true);
function checkFile(e) {
var files = e.target.files;
for (var i = 0, file; file = files[i]; i++) {
var fileName = file.name;
var fileExt = fileName.split(".")[fileName.split(".").length - 1].toLowerCase();
var fileSize = document.getElementById("uploadFile").files[0].size;
var fileSizeMB = (file.size / 2097152).toFixed(2);
if (!(fileExt === "jpg" || fileExt === "eps" || fileExt === "tif" || fileExt === "tiff") || fileSize > 2097152) {
alert("There is an error with the file you selected. Please check the file size and/or the file type.");
} else {
$("#uploadSubmit").prop("disabled", false);
}
}
};
Try
$("#uploadSubmit").removeAttr("disabled");
Hope it helps.
Sorry I can't just comment because it requires at least 50 reputation, wtf!
check if you have jQuery, I notice you're using getElementById at the beginning and somehow you're using jQuery selector for uplaodSubmit. Other than that, syntax looks correct to me.
And if you want to stick with pure JS, use:
document.getElementById('uploadSubmit').disabled = false
instead.
Good Luck.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="script/jquery-1.9.1.min.js"></script>
</head>
<script>
$(function() {
$('#uploadFile').bind('change', function() {
var filename = this.files[0].name.toLowerCase();
if ((filename.indexOf(".jpg") > -1)
|| (filename.indexOf(".png") > -1)) {
if(this.files[0].size<2000000){
$("#uploadSubmit").removeAttr("disabled");
alert("This is your solution");
}else{
alert("You cant get bigger than 2 MB");
}
} else {
alert("File format must jpg or png");
return false;
}
});
});
</script>
<body>
<p>Select a logo to upload</p>
<input type="file" id="uploadFile" class="upload" name="upfile"><br>
<input type="submit" id="uploadSubmit" disabled="disable" value="Upload Image">
</body>
I tried this I think this more helpful for you
$("#element").attr("disabled", false) OR $("#element").removeAttr("disabled").
I hope this first example is better with new jQuery version.
Related
I've the following code that checks if I file is .jpg,.jpeg or .png:
<!DOCTYPE html>
<html>
<body>
<input type="file" align="center" accept=".jpg,.jpeg,.png" onchange="this.size = Math.max(this.value.length, 7)+15;read(this)" id="myinput" style="min-width: 50px;"
/>
</body>
</html>
<script>
var myfile=""
async function read(input) {
var file = input.files[0];
var idxDot = file.name.lastIndexOf(".") + 1;
var extFile = file.name.substr(idxDot, file.name.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//fileContent = await readFile(file);
myfile=file
alert("Valid file selected!");
}else{
alert("Only jpg, jpeg or png allowed");
input.value = myfile;
}
}
</script>
I'm attempting that if a file different to that ones is selected the last value of a taken valid file displays.
But that only happens, at the beginning, after a valid file has been taken. if I choose another one the path shown in the input changes to that of the selected file even if it's not a valid one.
Is there any way to solve this issue so the path that displays is always the one of the last valid file?
a little bit of a hack but may give you what you need
var myfile={name:"none"};
function read(input) {
var file = input.files[0];
var idxDot = file.name.lastIndexOf(".") + 1;
var extFile = file.name.substr(idxDot, file.name.length).toLowerCase();
var span =document.getElementById('last');
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//fileContent = await readFile(file);
myfile=file
alert("Valid file selected!");
span.style.display='none';
}else{
alert("Only jpg, jpeg or png allowed");
input.value = '';
span.style.display='inline';
span.innerHTML = "Last valid File was: " + myfile.name
}
}
span{
display:none;
}
<!DOCTYPE html>
<html>
<body>
<input type="file" align="center" accept=".jpg,.jpeg,.png" onchange="this.size = Math.max(this.value.length, 7)+15;read(this)" id="myinput" style="min-width: 50px;"
/>
<span id='last'></span>
</body>
</html>
I'm working on a project and I need the user to upload only pdf files.
I'm trying to do this in the front-end so whenever the input detects a file type that is not a pdf should reject it. Everything seems correct. However, when I hover over the input it shows me that the wrong file is uploaded. So what should I do?
function changeName(elem) {
$("input[type='file']").
elem.on("change", function() {
var fileName = elem.val().split("\\").pop();
var fileExtension = elem.val().split(".").pop();
if (fileExtension === "pdf") {
elem.siblings(".Syllabus").text(fileName);
} else {
elem.siblings(".Syllabus").val('');
elem.siblings(".Syllabus").text('...');
alert('Only PDF files are accepted');
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="Syllabus fileReset">...</label>
<input type="file" accept="application/pdf" name="file1" onClick="changeName($(this));" required class="upload-button removable" />
This code works better than what you posted
$("input[type='file']").on("change", function(e) {
var elem = $(this);
elem.siblings(".Syllabus").text("...")
var fileName = elem.val().split("\\").pop();
var fileExtension = elem.val().split(".").pop();
if (fileExtension !== "pdf") {
elem.siblings(".Syllabus").text('Only PDF files are accepted')
elem.replaceWith(elem.val('').clone(true));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="Syllabus fileReset">...</label>
<input type="file" accept="application/pdf" name="file1" required class="upload-button removable" />
According to this: http://jsfiddle.net/Shiboe/yuK3r/6/ I can do it without any problem.
But,
I have got a multiple attribute in my input element and if i want to upload for example 8000 files catchEvent() function print out 0. Is any solution of this problem?
$(document).ready(function(){
$("#testInput").on('click', function(){
run();
});
function run(){
document.body.onfocus = catchEvent;
}
function catchEvent(){
console.log(document.getElementById("testInput").files.length);
document.body.onfocus = null;
}
})
<input id="testInput" type="file" name="test" multiple="multiple" />
You can get file info as follow code:
godzilla.onchange= function(){
var files = $(this)[0].files;
if (files.length > 0){
console.log("file selected="+files.length);
}
};
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
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