create text file using javascript - javascript

I want to create text file (notepad type file) using javascript. My code is given below but it is not working plz. Suggest me any solution for creating text file.
var txt = new ActiveXObject("Scripting.FileSystemObject");
var s = txt.CreateTextFile("D:\\test.txt", true);// means file is store in my D drive.
s.WriteLine('Hello');
s.Close(); `

you can try this:
(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);
})();
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>
Also you can show this DEMO

The following code snippet demonstrate create a text files using the jQuery and HTML5 file API. For the sake of simplicity, in this example I am using Bootstrap CSS framework for building the page.
$('#btnSave').click(function() {
if ('Blob' in window) {
var fileName = prompt('Please enter file name to save', 'Untitled.txt');
if (fileName) {
var textToWrite = $('#exampleTextarea').val().replace(/n/g, 'rn');
var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' });
if ('msSaveOrOpenBlob' in navigator) {
navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
} else {
var downloadLink = document.createElement('a');
downloadLink.download = fileName;
downloadLink.innerHTML = 'Download File';
if ('webkitURL' in window) {
// Chrome allows the link to be clicked without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.click(function(){
document.body.removeChild(event.target);
});
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
}
} else {
alert('Your browser does not support the HTML5 Blob.');
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Your HTML, CSS, and JavaScript playground.">
<title>HTML, CSS, JS Playground</title>
<meta content="width=device-width, initialscale=1" name="viewport">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" type="text/javascript"></script>
<script>
$(document ).ready(function() {
//Put your java script here
});
</script>
</head>
<body>
<div class="container">
<h1>Reading and Creating Text Files Using the HTML5 File API and jQuery</h1>
<div class="form-group">
<button type="button" class="btn btn-default" id="btnOpen">Open...</button>
<button type="button" class="btn btn-default" id="btnSave">Save</button>
</div>
<input type="file" id="exampleInputFile" accept=".txt,.csv,.xml" class="hidden">
<div class="form-group">
<textarea class="form-control" rows="15" id="exampleTextarea"></textarea>
</div>
</div>
</body>
source

Related

Camera permission dialogue box not appearing

So I've been trying to make a UI in which the user can upload his pictures to local system (To move from one location to images database by opening a file manager dialogue box) or take live pictures and add to the images database. I made this simple html file which is running well but after i try to run it with flask after creating a localhost , google chrome doesn't prompt for camera permission from above and somehow the permission is already granted but the camera doesn't work . Here is the code- app.py
import os
from flask import Flask, request, render_template, send_from_directory
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route("/")
def index():
return render_template("upload.html")
#app.route("/upload", methods=["POST"])
#for the intake of the folder name that needs to be created or selected in the dataset folder
def upload():
fold_nam=request.form["name"]
folder_name = request.form.get('superhero')
'''
# this is to verify that folder to upload to exists.
if os.path.isdir(os.path.join(APP_ROOT, 'files/{}'.format(folder_name))):
print("folder exist")
'''
#Change this target variable as per the device working in (set your own path address of the dataset folder)
target="/home" + str(fold_nam).lower()
print(target)
if not os.path.isdir(target):
os.mkdir(target)
print(request.files.getlist("file"))
for upload in request.files.getlist("file"):
print(upload)
print("{} is the file name".format(upload.filename))
filename = upload.filename
# This is to verify files are supported
ext = os.path.splitext(filename)[1]
if (ext == ".jpg") or (ext == ".png"):
print("File supported moving on...")
else:
render_template("Error.html", message="Files uploaded are not supported...")
destination = "/".join([target, filename])
print("Accept incoming file:", filename)
print("Save it to:", destination)
upload.save(destination)
# return send_from_directory("images", filename, as_attachment=True)
return render_template("complete.html", image_name=filename)
if __name__ == "__main__":
app.run(port=4555, debug=True)
index.html
<!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>
<form id="frm1" action="/action_page.php">
Name: <input type="text" name="fname"><br>
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>
<script type="text/javascript">
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function () {
realFileBtn.click();
});
realFileBtn.addEventListener("change", function () {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(
/[\/\\]([\w\d\s\.\-\(\)]+)$/
)[1];
} else {
customTxt.innerHTML = "No file chosen, yet.";
}
});
</script>
</form>
<div class="container">
<video id="video" width="300" height="300" autoplay="true"></video>
<button class="button" id="snap">Photo</button>
<canvas id="canvas" width="300" height="300"></canvas>
<br>
<a id="download" href="/images/myw3schoolsimage.jpg" download>download</a>
<div>
<input type="submit" value="Upload!" id="upload-button"><br>
</body>
<script>
$("#file-picker").change(function () {
var input = document.getElementById('file-picker');
for (var i = 0; i < input.files.length;i++) {
//koala.jpg, koala.JPG substring(index) lastIndexOf('a') koala.1.jpg
var ext = input.files[i].name.substring(input.files[i].name.lastIndexOf('.') + 1).toLowerCase()
if((ext == 'jpg') || (ext == 'png')) {
$("#msg").text("Files are supported")
}
else {
$("#msg").text("Files are NOT supported")
document.getElementById("file-picker").value = "";
}
}
});
</script>
<script src="./index.js"></script>
</html>
index.js
(() => {
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = document.getElementById("img")
var download = document.getElementById("download")
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
video.srcObject = stream;
video.play();
});
}
document.getElementById("snap").addEventListener("click", () => {
context.drawImage(video, 0, 0, 300, 300);
img.setAttribute("src", canvas.toDataURL("image/png"))
download.setAttribute("href", canvas.toDataURL("image/png"))
});
})()
All i want is to run the **index.html ** using flask with the camera running properly in localhost.
I know that my code is not in the finished state , but i'm stuck at this very place. I would like to mention that all my files are in proper directories and i have no indentation errors etc. Anyone who is willing to help is requested to mention every minute detail as I'm not very good at this .
Thankyou!

Toggle properties of anchor and image elements via JavaScript

I currently have a single web page that contains two elements:
image (wrapped in anchor, loads URL in iframe)
iframe (loads themes.html by default)
The image, on-click, toggles/switches the iframe between themes.html and styles.html, as well as the image source. However, despite the numerous tutorials and forum posts I have read online, I cannot get it to work.
How would I go about having the image toggle when clicked, as well as toggling the source of the iframe between the two HTML files?
<!DOCTYPE HTML>
<html>
<head>
<title>Manager</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body>
<div class="switch">
<a href="styles.html" target="switchframe" id="toggleURL" onclick="toggleURL();">
<img src="images/segment-theme.png" id="toggleImage" onclick="toggleImage();"/></a>
<iframe id="frame" name="switchframe" src="themes.html"></iframe>
</div>
<script>
function toggleImage() {
var img1 = "images/segment-theme.png";
var img2 = "images/segment-style.png";
var imgElement = document.getElementById('toggleImage');
imgElement.src = (imgElement.src === img1)? img2 : img1;
}
function toggleURL() {
var url1 = "themes.html"
var url2 = "styles.html"
var urlElement = document.getElementById('toggleURL');
urlElement.href = (urlElement.href === url1)? url2 : url1;
}
</script>
</body>
</html>
EDIT: I figure I could maybe have it just toggle the iframe's src property directly, but if I can't even get the image's src to toggle to begin with, I fear I won't be able to get that working either.
EDIT 2: I can get it to load styles.html in the iframe with the code below; however, I cannot get it to toggle back to themes.html:
function toggleURL() {
var url1 = "themes.html"
var url2 = "styles.html"
var urlElement = document.getElementById('frame');
urlElement.src = (urlElement.src === url1)? url2 : url1;
}
I believe you're having issues because you're using element.attribute instead of element.getAttribute('attribute-name').
Since image.src will return the absolute path www.domain.com/path/to/image.png where getAttribute returns the value specified in the element.
Also you need only one event handler for your case.
<html>
<head>
<title>Manager</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body>
<div class="switch">
<a href="styles.html" id="toggleURL" onclick="toggle(event);">
<img src="images/segment-theme.png" id="toggleImage" />
</a>
<iframe id="frame" src="themes.html"></iframe>
</div>
<script>
function toggle(e) {
e.preventDefault();
var img1 = "images/segment-theme.png";
var img2 = "images/segment-style.png";
var imgElement = document.getElementById('toggleImage');
var src = imgElement.getAttribute('src');
imgElement.setAttribute('src', (src === img1) ? img2 : img1)
var url1 = "themes.html"
var url2 = "styles.html"
var urlElement = document.getElementById('toggleURL');
var href = urlElement.getAttribute('href');
document.getElementById('frame').setAttribute('src', href)
urlElement.setAttribute('href', (href === url1) ? url2 : url1)
}
</script>
</body>
</html>

Saving data to a text file using javascript

I found a script to write the contents of a textbox to a text file, and show the download link.
But now I need help with modifying this code to save the text files in a specific location in the server once the button is clicked.
Here is the code:
<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>
Please advise.
You will need to learn backend development for server side practices. A client cant make any modification to the server without a backend in place. (That would be a huge security hole!) I would suggest learning NodeJS here: https://www.w3schools.com/nodejs/
Once you become more familiar and think you are ready to pick up this project again send me a direct message and I will point you in the right direction.

Javascript Read A Document and PDF [duplicate]

This question already has answers here:
How to extract text from a PDF in JavaScript
(8 answers)
Closed 8 years ago.
I am trying to extract the text from a document and pdf files and put them in a text area.
My code is at follows:
<html>
<head>
<title>FileReader Example</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
function upload(){
document.getElementById("image_src").click();
}
$("document").ready(function () {
$("#image_src").change(function () {
readBlob();
});
});
function readBlob() {
var files = document.getElementById('image_src').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function (evt) {
console.log(evt.target.result);
console.log(evt.target.data);
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
</script>
<style>
#image_src {
position:absolute;
left:-9999px;
}
#img {
cursor:pointer;
}
</style>
</head>
<body>
<div class="container">
<img id="img" src="images/ChooseFile.png" onclick="upload()" alt="hellp"/>
<input type="file" name="image_src" id="image_src" />
<pre id="fileDisplayArea"><pre>
<div id="byte_content"></div>
</div>
</body>
</html>
The only problem I am having is that text is being displayed as rubbish but if I upload a text file it works. What's going wrong?
PDF is a binary format , it may contain interactive elements such as annotations, form fields, video and Flash animation.
If you need to work with PDF documents i suggest looking into PDF.js project .
I have located some API Doc's that might help you getting started :
PDFJS.getDocument
getPage
getTextContent

Creating an option menu based on a text file?

I am trying to automatically create an option menu (using HTML and JavaScript) based on the contents of a text file. What I would like is for each option in the menu to be a line in the text document.
Here is the JavaScript:
function get_parameters() {
alert("get_parameters() called"); // these alerts are just to tell me if that section of the code runs
var freader = new FileReader();
var text = "start";
freader.onload = function(e) {
text = freader.result;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
With this code, all I'm trying to accomplish is reading the file and printing to the div "bottom_pane_options" but I can't find any reason why it doesn't work. If my way isn't the most efficient, could you please give me code that would work?
Thanks.
--EDIT--
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<title>Culminating</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
<script>
// Calling the Google Maps API
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js"></script>
</html>
You need to set the <div> text in the callback instead of right after you start loading:
freader.onload = function(e) {
text = freader.result;
/*************
** TO HERE **
************/
alert('file has been read');
}
/* MOVE THIS */
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
/*************/
Because the file was not read yet when you are runing div.innerHTML = div.innerHTML + text;.
That's why there are callbacks.
See https://developer.mozilla.org/en-US/docs/Web/API/FileReader :
The FileReader object lets web applications asynchronously read the
contents of files [...]
Use this instead :
freader.onload = function(e) {
text = freader.result;
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");

Categories