javascript accept only image not working - javascript

In my code I want to accept only image file.otherwise it will not accept and will give alert that its not image file.
I have done below code in jsfiddle:--
jsfiddle link
but the problem is it..It is not giving any message.what am I doing wrong?

https://jsfiddle.net/weufx7dy/2/
You forgot to add id on file element
<input type="file" id="file" name="fileUpload" size="50" />

You had used
var image =document.getElementById("file").value;
but forgot to give id to file control so give that
<input type="file" name="fileUpload" id="file" size="50" />
and try following code in w3schools tryit browser and use onClick event on submit button instead of onSubmit
<!DOCTYPE html>
<html>
<body>
<div align="center">
<form:form modelAttribute="profilePic" method="POST"enctype="multipart/form-data" action="/SpringMvc/addImage">
<input type="file" name="fileUpload" id="file" size="50" />
<input type="submit" value="Add Picture" onClick="Validate();"/>
</form:form>
</div>
<script>
function Validate(){
var image =document.getElementById("file").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.gif|\.GIF|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg,.gif");
document.getElementById("file").focus();
return false;
}
}
return true;
}
</script>
</body>
</html>

Use this :
userfile.addEventListener('change', checkFileimg, false);
function checkFileimg(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "jpg")) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Please make sure your file is in jpg format.\n\n";
alert(txt);
document.getElementById('userfile').value='';
}
}
}

Related

How do I validate multiple input fields at the same time

I'm trying to validate file type so only JPGs or PNGs can be submitted in my form. I've set it so onChange of the image upload field an alert pops up and the 'upload' button is hidden. However I have 5 fields and if I choose a correct filetype in another box the button is then shown even if the wrong filetype is still selected in another field. How can I clear the input field at the same time as triggering the alert if the filetype is wrong?
I've tried this.value = ""; between changing the class and the alert but I'm not sure of the correct syntax to clear the current box
function validate(fName){
splitName = fName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
if (fileType != 'jpg' && fileType != 'jpeg' && fileType != 'png'){
document.getElementById("uploadbutton").className = "hide";
alert("You must select a .jpg or .png, file.");
}
else {
document.getElementById("uploadbutton").className = "fwdbutton upload";
}
}
<div id="upload">
<h2>If possible, please could you include photographs of the following:</h2>
<p><label for='uploaded_file1'>Current boiler:</label> <input type="file" name="uploaded_file1" id="uploaded_file1" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p>
<p><label for='uploaded_file2'>Gas meter:</label> <input type="file" name="uploaded_file2" id="uploaded_file2" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p>
<p><label for='uploaded_file3'>Boiler pipe work:</label> <input type="file" name="uploaded_file3" id="uploaded_file3" class="uploadfields" accept="image/png, image/jpg, image/jpeg"onChange="validate(this.value)">X</p>
<p><label for='uploaded_file4'>Outside flue:</label> <input type="file" name="uploaded_file4" id="uploaded_file4" class="uploadfields" accept="image/png, image/jpg, image/jpeg"onChange="validate(this.value)">X</p>
<p><label for='uploaded_file5'>Anything else relevant:</label> <input type="file" name="uploaded_file5" id="uploaded_file5" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p><br />
<input class="backbutton showmoved" type="button" value="<< back" /> <input class="fwdbutton upload" id="uploadbutton" type="button" value="upload >>" />
<p><a class="nophotos" id="nophotos">I have no photos >></a></p>
</div>
Many thanks for any advice,
Helen
Please try this.
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
oInput.value = "";
return false;
}
}
}
return true;
}
File 1: <input type="file" name="file1" onchange="ValidateSingleInput(this);" /><br />
File 2: <input type="file" name="file2" onchange="ValidateSingleInput(this);" /><br />
File 3: <input type="file" name="file3" onchange="ValidateSingleInput(this);" /><br />
use a counter to see if you have more errors:
var counter= 0;
function validate(fName){
splitName = fName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
if (fileType != 'jpg' && fileType != 'jpeg' && fileType != 'png'){
alert("You must select a .jpg or .png, file.");
counter = counter + 1;
}
if (counter !=0){
document.getElementById("uploadbutton").className = "hide";
}else{
document.getElementById("uploadbutton").className = "fwdbutton upload";
}
}
each time you run the function it will check if you have an error. This code otherwise is an example and doesn't handle if you fix a previously marked error.
My advice is to redesign the code to check each input once on button click and trigger the alert of the submission. Instead of doing so that is overcomplicating things. So leave the button always visible and run the function on uploadButton click
Hope this will help you. Initially Upload button is hidden when all the valid files are selected you will see upload button and any invalid type will give you alert.
var isValid = [0];
var sumTotal=0;
function validate(fileNo){
var files = event.target.files;
var filetype = files[0].type;
if (filetype == 'image/jpeg' || filetype == 'image/jpeg' || filetype == 'image/png'){
isValid[fileNo]=1;
}else{
alert("You must select a .jpg or .png, file.");
isValid[fileNo]=0;
}
sumTotal = isValid.reduce(function(a, b) { return a + b; }, 0);
if(sumTotal==5){
document.getElementById("uploadbutton").style.display="block";
}else{
document.getElementById("uploadbutton").style.display="none";
}
}
<div id="upload">
<h2>If possible, please could you include photographs of the following:</h2>
<p><label for='uploaded_file1'>Current boiler:</label> <input type="file" name="uploaded_file1" id="uploaded_file1" class="uploadfields" onChange="validate(1)">X</p>
<p><label for='uploaded_file2'>Gas meter:</label> <input type="file" name="uploaded_file2" id="uploaded_file2" class="uploadfields" onChange="validate(2)">X</p>
<p><label for='uploaded_file3'>Boiler pipe work:</label> <input type="file" name="uploaded_file3" id="uploaded_file3" class="uploadfields" onChange="validate(3)">X</p>
<p><label for='uploaded_file4'>Outside flue:</label> <input type="file" name="uploaded_file4" id="uploaded_file4" class="uploadfields" onChange="validate(4)">X</p>
<p><label for='uploaded_file5'>Anything else relevant:</label> <input type="file" name="uploaded_file5" id="uploaded_file5" class="uploadfields" onChange="validate(5)">X</p><br />
<input class="backbutton showmoved" type="button" value="<< back" /> <input class="fwdbutton upload" style="display: none;" id="uploadbutton" type="button" value="upload >>" />
<p><a class="nophotos" id="nophotos">I have no photos >></a></p>
</div>
You can use the following regular expression to check whether the file valid.
/\.(jpe*g|png)$/gi
And then you can use the test() method to check if the file is valid in your if statement.
if(/\.(jpe?g|png)$/gi.test(s)) {
//TODO
}

HTML multiple fileread

HTML Code:
<input type="file" name="img1" id="img1" required>
<input type="file" name="img2" id="img2">
<input type="file" name="img3" id="img3">
<input type="file" name="img4" id="img4">
jQuery Code:
for(var i = 1; i <= 4; i++){
if($("#img"+i).val() != ''){
file = document.getElementById('img' + i).files[0];
fileread(file);
}
}
function fileread(file){
var result = '';
reader = new FileReader();
reader.onload = function(){
result = reader.result;
//return result;
localStorage.setItem("lostimage1", result);
}
reader.readAsDataURL(file);
}
I want to read multiple files when user click on submit button. but it not working. How can I resolve this error? please help me.
Using Jquery and each() method I suggest this:
var checkValue;
var valueArray=[];
$('#button').on('click',function(){
$('input').each(function(){
checkValue=$(this).val();
if(checkValue===''){
return;
}
valueArray.push(checkValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="img1" id="img1" required>
<input type="file" name="img2" id="img2">
<input type="file" name="img3" id="img3">
<input type="file" name="img4" id="img4">
<button id="button">Click Me</button>
Attach click event to <input type="submit">, call event.preventDefault() to prevent <form> submission, use .each() to iterate <input type="file"> elements, pass this.files[0] to readfile function.
Adjust within FileReader load handler to not overwrite same key at localStorage.
FileReader throws an error if a Blob or File object is not passed as parameter to .readAsDataURL(), for example, ifis clicked andfilereadis called in loop and one ofelements.filesproperty doe not containFileobject inFileList. Check if element.fileshas.lengthgreater than0before callingfilereadreferencing the.files[0]property of the current` element.
$(function() {
function fileread(file, id) {
var reader = new FileReader();
reader.onload = function() {
localStorage.setItem("lostimage" + id, reader.result);
}
reader.readAsDataURL(file);
}
$("input[type=submit]").on("click", function(e) {
e.preventDefault();
$(":file[id^=img]").each(function() {
if (this.files.length) fileread(this.files[0], this.id.replace(/\D/g, ""))
})
});
});
plnkr http://plnkr.co/edit/1Sec8uWlK2pbXMTlfpCj?p=preview

Multi File upload "files[]" javascript validation

On my site I have multi file upload form with fields:
<input name="files[]" type="file" id="files" size="30" />
<input name="files[]" type="file" id="files" size="30" />
<input name="files[]" type="file" id="files" size="30" />
and I want to validate this fields with javascript code, I know how to get value for some simple fields with javascript but I don`t know how to get values from this fields with names "files[]", how javascript see this fields, array or...?
How to apply validation of size and file type using javascript
<!DOCTYPE html>
<html>
<body>
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<button onclick="myFunction()">Get File Name-Type-Size</button>
<script>
function myFunction() {
var input, file;
if (!window.FileReader) {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
var input=document.getElementsByName('files[]');
for(var i=0;i<input.length;i++){
var file = input[i].files[0];
bodyAppend("p", "File " + file.name + " is " + formatBytes(file.size) + " in size"+" & type is "+ fileType(file.name));
}
}
//function to append result to view
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
//function to find size of file in diff UNIT
function formatBytes(bytes,decimals) {
if(bytes == 0) return '0 Byte';
var k = 1000;
var dm = decimals + 1 || 3;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
//function to find file type
function fileType(filename){
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}
</script>
</body>
</html>
Check this now you can put conditions on type of file & size.
// Try this jQuery ;)
$("form").on('change', 'input[type=file]', function() {
var file;
var this = $(this);
if (file = this.files[0])
{
var img = new Image();
img.onload = function () {
// correct
// check alert(img.src)
}
img.onerror = function () {
//error info
};
img.src = _URL.createObjectURL(file);
}
}
<!DOCTYPE html>
<html>
<body>
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<button onclick="myFunction()">Get File Type</button>
<script>
function myFunction() {
var file=document.getElementsByName('files[]');
for(var i=0;i<file.length;i++){
console.log(file[i].value);
}
}
</script>
</body>
</html>
you can get files name like this.
Thanks Bhavik vora But already done with this one
<html>
<head>
<title>client-side image (type/size) upload validation</title>
<meta charset=utf-8>
<style>
</style>
</head>
<body>
<form><fieldset><legend>Image upload</legend>
<input type="file" name="file[]" onchange="getImg(this,100,'jpeg|png')">
<input type="file" name="file[]" onchange="getImg(this,100,'jpeg|png')">
</fieldset>
</form>
<script>
function getImg(input,max,accepted){
var upImg=new Image(),test,size,msg=input.form;
msg=msg.elements[0].children[0];
return input.files?validate():
(upImg.src=input.value,upImg.onerror=upImg.onload=validate);
"author: b.b. Troy III p.a.e";
function validate(){
test=(input.files?input.files[0]:upImg);
size=(test.size||test.fileSize)/1024;
mime=(test.type||test.mimeType);
mime.match(RegExp(accepted,'i'))?
size>max?(input.form.reset(),msg.innerHTML=max+"KB Exceeded!"):
msg.innerHTML="Upload ready...":
(input.form.reset(),msg.innerHTML=accepted+" file type(s) only!")
}
}
</script>
</body>
</html>

how to browse multiple image or file in jquery?

I want to show multiple files or images after browse from system not uploaded on server can we show this using jquery?
I goggled it and find there is way to show and upload on server:
http://www.dropzonejs.com/
But. I only want to show images or file in this there is drag and drop functionality also present can we use this plugin.
But, when I use this plugin in fiddle it show only attached file name not display image why?
Here is fiddle:
http://jsfiddle.net/my50a3uh/1/
<form id="my-awesome-dropzone" action="/target" class="dropzone"></form>
<input type="file" name="file" />
I hope it may be useful for you.It is running well.
Live Working Demo
HTML Code:
<form enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
<output id="filesInfo"></output>
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
JS Code
function fileSelect(evt) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var files = evt.target.files;
var result = '';
var file;
for (var i = 0; file = files[i]; i++) {
// if the file is not an image, continue
if (!file.type.match('image.*')) {
continue;
}
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
var div = document.createElement('div');
div.innerHTML = '<img style="width: 90px;" src="' + evt.target.result + '" />';
document.getElementById('filesInfo').appendChild(div);
};
}(file));
reader.readAsDataURL(file);
}
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
document.getElementById('filesToUpload').addEventListener('change', fileSelect, false);

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Is it possible to save textinput (locally) from a form to a textfile, and then open that document to use it later on?
Just using HTML, javascript and jQuery. No databases or php.
/W
It's possible to save only if the user allow it to be saved just like a download and he must open it manually, the only issue is to suggest a name, my sample code will suggest a name only for Google Chome and only if you use a link instead of button because of the download attribute.
You will only need a base64 encode library and JQuery to easy things.
// This will generate the text file content based on the form data
function buildData(){
var txtData = "Name: "+$("#nameField").val()+
"\r\nLast Name: "+$("#lastNameField").val()+
"\r\nGender: "+($("#genderMale").is(":checked")?"Male":"Female");
return txtData;
}
// This will be executed when the document is ready
$(function(){
// This will act when the submit BUTTON is clicked
$("#formToSave").submit(function(event){
event.preventDefault();
var txtData = buildData();
window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
});
// This will act when the submit LINK is clicked
$("#submitLink").click(function(event){
var txtData = buildData();
$(this).attr('download','sugguestedName.txt')
.attr('href',"data:application/octet-stream;base64,"+Base64.encode(txtData));
});
});
<!DOCTYPE html>
<html>
<head><title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="base64.js"></script>
</head>
<body>
<form method="post" action="" id="formToSave">
<dl>
<dt>Name:</dt>
<dd><input type="text" id="nameField" value="Sample" /></dd>
<dt>Last Name:</dt>
<dd><input type="text" id="lastNameField" value="Last Name" /></dd>
<dt>Gender:</dt>
<dd><input type="radio" checked="checked" name="gender" value="M" id="genderMale" />
Male
<input type="radio" checked="checked" name="gender" value="F" />
Female
</dl>
<p>Save as TXT</p>
<p><button type="submit"><img src="http://www.suttonrunners.org/images/save_icon.gif" alt=""/> Save as TXT</button></p>
</form>
</body>
</html>
BEST solution if you ask me is this.
This will save the file with the file name of your choice and automatically in HTML or in TXT at your choice with buttons.
Example:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
function addTextHTML()
{
document.addtext.name.value = document.addtext.name.value + ".html"
}
function addTextTXT()
{
document.addtext.name.value = document.addtext.name.value + ".txt"
}
<html>
<head></head>
<body>
<form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">
<textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea>
<br>
<input type="text" name="name" value="" placeholder="File Name">
<input type="submit" onClick="addTextHTML();" value="Save As HTML">
<input type="submit" onClick="addTexttxt();" value="Save As TXT">
</form>
</body>
</html>
From what I understand, You have to save a user's input locally to a text file.
Check this link. See if this helps.
Saving user input to a text file locally
This will work to both load and save a file into TXT from a HTML page with a save as choice
<html>
<body>
<table>
<tr><td>Text to Save:</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" cols="80" rows="25"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
</table>
<script type="text/javascript">
function saveTextAsFile()
{
var textToSave = document.getElementById("inputTextToSave").value;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
</body>
</html>
You can use localStorage to save the data for later use, but you can not save to a file using JavaScript (in the browser).
To be comprehensive:
You can not store something into a file using JavaScript in the Browser, but using HTML5, you can read files.
Or this will work too the same way but without a save as choice:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
}//]]>
</script>
</head>
<body>
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "qm5AG"
}], "*")
}
</script>
</body>
</html>
You cannot save it as local file without using server side logic. But if that fits your needs, you could look at local storage of html5 or us a javascript plugin as jStorage
Answer is YES
<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>
<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>
</form>
</body>
</html>

Categories