I was trying to pass user inputted data in HTML form to csv file on local drive.
But seems some error in it.
I have tried below code even that is copied from other sources.
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\sample.txt";
var file = OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
</br></br></html>
CSV file is not getting created and cant get any error in HTML.
You were not using the variable fso to call OpenTextFile, you should also keep in mind that IE has permissions to write in the path
This should work for you:
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\Users\\yourUser\\sample.csv";
var file = fso.OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
You can also use this solution that works for several browsers:
<html>
<head>
<script language="javascript">
function downloadCSV(form) {
const content = 'Write your csv content here!!';
const mimeType = 'text/csv;encoding:utf-8';
const fileName = 'download.csv';
const a = document.createElement('a');
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([content], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
}
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="downloadCSV(this.form)">
</form>
</body>
</html>
Related
I'm trying to create a form with HTML and javascript to be able to retrieve 3 different inputs from the user, combine them into 1 form in json format, and save the file into a local file location. Below is what I currently have. (I am unclear how I am able to save a json string to a local file location. Thank you for your time in advance. (I am a javascript and html novice)
<header class="banner">
<h1 style="color:blue">HTML User Input to local file location</h1><main>
<form id="myform" type="post">
<fieldset>
<legend style="color:blue">Sign Up</legend>
<p style="color:red">Write your con-fig codes below</p>
<div class="elements">
<label for="Input1">Input1 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input1"
name="Input1" size="25" />
</div>
<div class="elements">
<label for="Input2">Input2 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input2"
name="Input2" size="25" />
</div>
<div class="elements">
<label for="Input3">Input3 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input3"
name="Input3" size="25" />
</div
<div class="submit">
<input type="submit" id="btn" name="submit" class="btn" value="Send" />
</div>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function(e) {
var jsonData = {};
var formData = JSON.stringify($("#myForm").serializeArray());
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
e.preventDefault();
});
});
</script>
</main>
This has definitely been asked before in multiple places. Like Here and Here. Code copied from one of the links below
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
Credit to #Rafał Łużyński.
Please search for the solutions better before actually asking a question.
I want to use a different button to upload files to a form. Therefore, i hide the standard upload file button. However, i do want to display the filename when a user uploads a file.
Using wordpress contact form 7, i already tried putting a JS function on the label, but that doesnt work.
<label for="fileInput" class="custom-file-upload" onclick="displayfilename()">Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<script>
function displayfilename()
$('#fileInput').change(function(){
var filename = $(this).val().split('\\').pop();
});
</script>
The filename should be displayed next to the label.
You can use Event.target along with triggering the change event.
Please Note: You also have syntax error in your code (missing the {.......} part of the function displayfilename).
$('#fileInput').change(function(e){
var filename = e.target.files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
OR: You can also use this object:
$('#fileInput').change(function(){
var filename = $(this)[0].files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
$('#fileInput').change(function(e){
var filename = e.target.files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
You can access the file name in this way:
<label for="fileInput" class="custom-file-upload" onclick="displayfilename()">Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<script>
function displayfilename()
$('#fileInput').change(function(e) {
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
</script>
Here's a custom <button> and a custom filename <span>:
$('.choosefile').click(function () {
$('#fileInput').click();
});
$('#fileInput').change(function(e) {
var filename = this.files[0].name;
$('.fileuploadspan').text(filename);
});
input[type=file] {
display: none
}
.choosefile, .fileuploadspan {
font-family: "Comic Sans MS"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload">Choose file</label>
<button class="choosefile">Browse...</button>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label for="fileInput" class="custom-file-upload">Choose file
<input id="fileInput" name="fileInput" type="file" onchange="uploadPreview(this)" style="display:none"/>
</label><br>
<span class="fileuploadspan">No file selected</span>
</body>
</html>
js
uploadPreview = function (fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var reader = new FileReader();
reader.onload = function (e) {
var filename = file.name;
filename = filename.replace('.jpg', '');
filename = filename.replace('.jpeg', '');
filename = filename.replace('.png', '');
filename = filename.replace('.gif', '');
filename = filename.replace('.bmp', '');
$('.fileuploadspan').text(filename);
return;
};
reader.readAsDataURL(file);
}
}
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>
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='';
}
}
}
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>