I have this input type, if I upload a file with less than 8 length add zeros, but what I need is to change my input with the new name.
<body>
<input type="file" id="upload" />
<script>
$(document).ready(function(){
$('#upload').change(function(e){
var fileName = e.target.files[0].name;
var newName = fileName.substring(0,fileName.length-4);
while(newName.length<8){
newName = "0"+newName;
}
console.log(e.target.files[0].name=newName);
});
});
</script>
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 did a script that check the image width and remove the image if the width is lesser than certain amount.
The image field is required and after I removed it, it still passed the file validation.
sample: http://jsfiddle.net/AUQYv/3/
<form action="">
<input type="file" id="file" required />
<input type="submit" value="Submit">
</form>
Javascript
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
if(this.width<490||this.height<175){
$("#file").val("").change();
}
};
img.onerror = function () {
alert("not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
Your conditional statement is setting file = this.files[0]. Change to ==
Edit:
Since both commenters pointed out that I was wrong, replace
$("#file").val("").change():
with
$("#file").replaceWith($("#file").clone());
Try with this.
<form action="" id="form" method="post">
<input type="file" id="file" required accept='image/png, image/gif, image/jpeg, image/jpg'/>
//your button submit
Submit
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//When click the button
$('#submitForm').click(function(){
var validation = true; //Var to validation true
if($('#file').val()){ //There's image?
if($('#file').width()<490 || $('#file').height()<175){
validation = false;
}
}else{
validation = false;
}
//Is true?
if(validation){
$('#form').submit();
}else{
alert("select a image");
}
});
</script>
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.
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 have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:
function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
default:;
} // switch
} // ff_uploadimages_action
ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.
Here's one way to do it
document.getElementById('upload').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename').value = filename;
}
<input id="upload" type="file" />
<input id="filename" type="text" />
you don't mention jQuery but given it's popularity here's the same solution using jQuery
jQuery:
$('#upload').change(function() {
var filename = $(this).val();
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
$('#filename').val(filename);
});
Demo:
http://jsfiddle.net/pxfunc/WWNnV/4/
HTML:
<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />
JS:
function uploadOnChange(e) {
var filename = e.value;var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex +1);
}
document.getElementById('filename').value = filename;
}
A shorter way in jQuery would be the following:
HTML
<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>
jQuery
$("#buttonChooseFile").click(funtion()({
$("#inputFile").click();
});
$("#inputFile").change(function(){
var fileName = $("#inputFile").prop('files')[0]["name"];
$("inputDisplayFileName").val(fileName);
});
In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.