Get the extension of a file but can't get the filename - javascript

I am trying to check if a file has a valid extension or not. The problem is that when I give the file a random extension like .txt it doesn't get caught.
I think the problem is that I am not actually getting the full filename.
<script type="text/javascript">
function getExtension(fileName)
{
var parts = fileName.split('.');
return parts[parts.length - 1];
}
function isVideo(fileName)
{
var ext = getExtension(fileName);
switch (ext.toLowerCase())
{
case 'mp4': return true;
}
return false;
}
function check()
{
var f = document.getElementsByID('file');
if(isVideo(f.value) && document.getElementById('file').value)
{
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
The PHP form:
<?php
$nexturl = "http://localhost/index.php";
?>
<form action="<?php echo($response->url); ?>?nexturl=<?php echo(urlencode($nexturl)); ?>" method="post" enctype="multipart/form-data" onsubmit="return check();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
Bad file type.
</div>
<input type="hidden" name="token" value="<?php echo($response->token); ?>"/>
<input type="submit" value="go" />
</form>
</php>

You could first obtain the file extension and then do what you need to with it:
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
alert(theReturn); //returns .zip
So, in your code, you would need to switch your switch statement to the following:
function isVideo(fileName)
{
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
switch (theReturn.toLowerCase())
{
case '.mp4': return true; //make sure it's .mp4 instead of just mp4
}
retrun false
}
EDIT
Example to get file name and extension of uploaded file to FileUpload control:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input id="File1" type="file" />
<input type="button" id="btnGetExt" value="Get File Extension"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
btnGetExt.onclick = function () {
var patt1 = /\.[0-9a-z]+$/i;
var fileName = document.getElementById('File1').value;
alert(fileName);
var theReturn = fileName.match(patt1);
alert(theReturn);
}

Related

I want to display google script single cell value in html text box on button event

I am totally new and try to learn the script...pls someone help to resolve this issue
simply i wanna to get google script cell value and show to this in text box
GS code
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('WebAppSecure');
htmlOutput.message = '';
return htmlOutput.evaluate();
}
function getValues(){
var url = "url link";
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("Sheet4");
var getRange=webAppSheet.getRange(2,1).getValues();
console.log(getRange);//output value :23:43 PM Info Sunil
}
html side
function getresult(){
google.script.run.withSuccessHandler(function(output) {
var iterm=document.getElementById("dname").value;
}).getValues(name);
console.log(name);
}
<input type="text" id="dsrn" />
<input type="button" id="button2" value="ID_Search1" onclick="getresult()"/>
I don't wish to create a doGet() so here's the same thing done with a dialog:
GS:
function launchMyDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'),'Dialog Title');
}
function getMyValue() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
return sh.getRange(2,1).getValue();
}
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="text" id="txt"/>
<br /><input type="button" value="Get Data" onClick="getValue();" />
<script>
function getValue() {
google.script.run
.withSuccessHandler((v) => {document.getElementById("txt").value = v;})
.getMyValue();
}
console.log("my code")
</script>
</body>
</html>

Error uploading file to Parse

I am trying to load file (pdf) into parse, but nothing is showing up in my parse so I am assuming an error lies in the following code (note I created a new custom class scan).
<HTML>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<form id="fileupload" name="fileupload" enctype="multipart/form-data" method="post">
<input type="file" id="pic">
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
Parse.initialize("id", "id");
var products = Parse.Object.extend("Product");
var fileUploadControl = $("#pic")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
}
parseFile.save().then(function() {
//The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
</script>
</head>
</body>
</HTML>
Any help would be greatly appreciated.

On clicking the submit button it is not giving appropriate result

Hello ,
I am having some problem with javascript & Html..In my code i am reading excel file from directory and showing some output..for this i have a file input type and a Button...what is happening here is when i select the xls file and click on submit button Choose a file widow is opening every time when i am clicking on the submit button ..
the code is as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Speedometer HTML5 Canvas</title>
<script src="script copy.js"></script>
</head>
<body onload='draw(0);'>
<canvas id="tutorial" width="440" height="220">
Canvas not available.
</canvas>
<div>
<form id="drawTemp">
<input type="text" id="txtSpeed" name="txtSpeed" value="20" maxlength="2" />
<input type="button" value="Draw" onclick="drawWithInputValue();">
<input type=file id="fileInput" value="">
<input type=button value="submit" onclick="readdata(1,1);">
</form>
</div>
</body>
</html>
<script type="text/javascript" language="javascript">
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls", ".csv");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
// Use the <input type='file'...> object to get a filename without showing the object.
document.all["fileInput"].click();
var fileName = document.all["fileInput"].value;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open(fileName);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
}
catch (ex) {
alert(ex);
}
}
</script>
Every time i click on the submit button it opens the choose window to choose file ..why my button is behaving like file type input..
It's opening the "choose file" dialog because of this line in your Javascript:
document.all["fileInput"].click();
If you remove that, you won't get this behaviour.
document.all["fileInput"].click();
when you click on submit this line in the readdata() function is programmatically clicking on the choose file button.

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

how to get file size in javascript or jquery with rails

how to get file size in javascript or jquery with rails here by word size i means to say content size of file like 100kb.
here i got some methods like size or file size but its not working for me
my ruby code is
<%= upload_form.file_field :upload_file_name1,:onchange =>"return validateFileExtension(this)"%>
function validateFileExtension(fld) {
alert(fld.value.fileSize);
if(!/(\.jpg|\.gif|\.png)$/i.test(fld.value)) {
alert("Invalid file type! Kindly upload in a JPG, GIF or PNG format!");
fld.parentNode.innerHTML = fld.parentNode.innerHTML;
fld.focus();
return false;
}
return true;
}
<html>
<head>
<script language="JavaScript">
function A()
{
var oas = new ActiveXObject("Scripting.FileSystemObject");
var d = document.a.b.value;
var e = oas.getFile(d);
var f = e.size;
alert(f + " bytes");
}
</script>
</head>
<body>
<form name="a">
<input type="file" name="b">
<input type="button" name="c" value="SIZE" onClick="A();">
</form>
</body>
</html>

Categories

Resources