I wanted to try giving an output to a file using a Small screen on HTML. Everytime I click on the button I want the text in the file to be replaced. This is the code I wrote:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>This is Web App</title>
</head>
<script>
function createDoc()
{
var doc=document.open("answer.txt","replace");
var txt="<html><body>You clicked Allow</body></html>";
doc.write(txt);
doc.close();
}
function createDoc2()
{
var doc=document.open("answer.txt","replace");
var txt="<html><body>You clicked Deny</body></html>";
doc.write(txt);
doc.close();
}
</script>
<body>
<h1> This is the visitor at your house</h1>
<img src = "./images/chef.gif" width="130" height="101" />
<br />
<button name="Yes" type="button" onclick="createDoc()">Allow! </button>
<button name="No" type="button" onclick="createDoc2()">Deny! </button>
</body>
</html>
I know it is not the correct way to do it but am trying to learn. Please help me and point out my mistakes and tell me how to correct them if possible. I know there might be plenty. I am just trying to teach myself at this point. Your help is much appreciated.
If you just want to download a file generated by your page, this question may help:
Download data url file
The idea is that you need to encode your data as base64 (not hard, modern browsers support btoa) and direct the browser to open it. If you trick it by giving the file a mime-type it doesn't know how to open (such as application/octet-steam), it will download the file instead of displaying it.
The problem with this solution is that you cannot name the file.
If you want to name the file, I'd POST the data to your webserver, write it to a file on the server, then do a window.open with the path to the file. This will allow you to download the file in question.
There's a draft in progress to allow Javascript to write to a file directly, but this file will be in a sandboxed location that users don't have direct access to. This is only for web-apps to store large amounts of data on the client. From your question, this is likely not what you want. Try one of the above solutions.
Related
I know that in tkinter it is possible to open file dialogue box, but is there any way to do it in eel using python or even in javascript so that the download location can be obtained instead of hard coding to change the directory each time.
I used PyTube library of python,
from pytube import YouTube
link = input(" Enter YouTube video URL: ")
video = YouTube(link)
stream = video.streams.get_highest_resolution()
stream.download('local path')
And i created front end using front end technologies, it has only a box to paste url and a submit button.
On clicking submit button I'd want chrome to show a dialogue box to choose the download location to pass it inside stream.download('local path')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Downloader</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<h1>Downloader</h1>
<div class="line"></div>
<form action="">
<label for="">Enter YouTube video URL</label>
<input type="text" class="youtubeUrl" placeholder="Paste the URL here">
<button>Download</button>
</form>
</div>
</body>
</html>
Didn't give any class to the form, because it is going to be the only one in the web app.
Selecting a custom download location using pure JavaScript can be a pain because browser implementations severely limit the information (and access) they give you about the user's filesystem for security reasons. A web search for something like "HTML set custom download location" will bring up relevant results.
The good news here is that you can delegate that work Python, which will more easily allow you to select a download location (since Python is running outside of the browser's context). Since you already need to expose a Python function in order to get your Python code to run, just put the dialog box in that context... something like:
import tkinter
import eel
from pytube import YouTube
from tkinter import filedialog
root = tkinter.Tk()
root.withdraw() # hide this root window
eel.init("web")
#eel.expose
def download(link):
download_location = filedialog.asksaveasfile() # this will open the Save As dialog
video = YouTube(link)
stream = video.streams.get_highest_resolution()
stream.download(download_location.name)
eel.start("index5.html")
There are some non-standard/trick alternative options that may be supported on your target browser, so check out webkitdirectory, File_and_Directory_Entries_API, FileSaver.js, and Using HTML5/JavaScript to generate and save a file for more information about those if you want to stick with JavaScript.
Is it possible to move a file from my local machine to another machine in my network using HTML5 and JavaScript only? If any jQuery or JavaScript plugin available can be used for this.
Thank you in advance.
Assuming you mean client side JavaScript embedded in a webpage: No, it isn't.
You can select a file using an HTML file input.
You can send that file using form submission or Ajax
However:
You can't delete the file from the client at all.
You can't make the destination machine do anything with the file submission.
If you were to use Node.js to run some or all of the JavaScript then:
You could write a (non-browser based) client that could send the file and delete the local version. This wouldn't have to use HTTP, so you could use SMB or SSH to transfer it instead.
You could write a server (such as an HTTP) to receive the file and save it to disc.
Actually Quentin is wrong in theory here, since "remote" was never mentioned. If your "other machine" has shares where you can save, you can run my example below. So YES, it is possible but it depends on file size. You can read out the params from a request with client-side code like JavaScript. File sizes acceptance defer per browser but this is tweakable with Chromium/Chrome for instance. It is even possible on some OS-es to do basic authentication by using the in URL authentication notation on the form action. So what you could do is:
Make a UI which makes you select a file in a form with method "GET"
On submit create a base64 encoded string with the FileReader API
Basic example without the FileReader API (index.html):
<!DOCTYPE HTML>
<html>
<head>
<title>"Upload" locally</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<form method="get" action="iwillsave.html">
<div class="input-group">
<label for="file">Pick a file:</label>
<input id="file" name="file" type="file">
</div>
<div class="form-actions">
<button type="submit">Submit</button>
</div>
</form>
</body>
</html>
In your "Save" page handle the file decoding and save it with the FileSystem API
Basic example without the FileSystem API (iwillsave.html):
<!DOCTYPE HTML>
<html>
<head>
<title>"Upload" locally</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="result"></div>
</body>
<script type="text/javascript">
function getParam(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search)) return decodeURIComponent(name[1]);
};
window.onload = function(){
var file = getParam('file');
document.getElementById('result').innerHTML = file;
};
</script>
</html>
I want to save json file to my application's directory using javascript. how to do it? my code only opens a new tab when you click download button and display the content of my json file. I am allowed to use client-side scripting only. I've tried this code but not working.
NOT WORKING CODE:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("location", true);
s.WriteLine(json);
s.Close();
Here's my code..
HTML CODE:
<!doctype html>
<html manifest="survey.manifest">
<head>
<title>Offline Survey Application</title>
<link rel="stylesheet" href="styles/survey.css" type="text/css">
<script type="text/javascript" src="scripts/survey.js"></script>
</head>
<body>
</body>
</html>
Javascript code
window.onload=function myFunction()
{
var btn=document.createElement("BUTTON");
btn.setAttribute('id', 'dButton');
btn.setAttribute('value', 'download');
var t=document.createTextNode("DOWNLOAD");
btn.appendChild(t);
document.body.appendChild(btn);
btn.onclick=function clickedFunction(){
var url = "http://localhost/JSONFiles/survey.json";
window.open(url, 'download');
}
};
thanks in advance friends! :)
What you are trying to do would kill a lot of kittens.
For safety reasons, a web page cannot use activeX objects on a whim, nor access the local computer resources like file system in any way except what is allowed by standard (basically the cookies and local storage files).
That would allow any Russian hacker and his rabid dog to wreak havoc on computers all over the planet.
You can, however, try to use local storage if your json files are not too bulky and you don't expect to reuse them from another application.
If you plan on downloading json files, just point to them (i.e. put a link to whatever .json file somewhere on your page) and when the user clicks on such a link the browser will pop a save requester to let the user free to save the files in a location of his/her choosing.
If all you're trying to do is get a file on your server to download automatically instead of be viewed in the browser, you just need to set the Content-Disposition header the file is sent to the client with to "attachment". The easiest way to do that is to modify the config files for whatever server your using to add a rule for files of type .json. The exact methodology will differ depending on your server, though.
I'm using HTML5 File API to get some document(.doc/.docx/.pdf) uploaded. And I want to show that document preview before uploading it to server. Is there any way to do such thing on client side?
P.S. Google Docs Viewer isn't ok, because it requires document to be accessible from the internet.
I have tried to create little example and that would display PDF Preview before uploading PDF file.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript PDF Viewer Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function PreviewImage() {
pdffile=document.getElementById("uploadPDF").files[0];
pdffile_url=URL.createObjectURL(pdffile);
$('#viewer').attr('src',pdffile_url);
}
</script>
</head>
<body>
<input id="uploadPDF" type="file" name="myPDF"/>
<input type="button" value="Preview" onclick="PreviewImage();" />
<div style="clear:both">
<iframe id="viewer" frameborder="0" scrolling="no" width="400" height="600"></iframe>
</div>
</body>
</html>
Not sure if anyone still checks this thread, but i thought i'd share what i did.
Directly showing a preview isn't possible, but you can create a blob object of the selected file. Something like this (jQuery):
$('#input').change(function (event) {
var file = URL.createObjectURL(event.target.files[0]);
$('element').append('' + event.target.files[0].name + '');
});
This link will open a new browser tab and shows/downloads the file. This isn't really pretty but it works.
Here's an example: https://jsfiddle.net/j9gw023b/3/
No. This is not possible.
You want the browser to view a datafile it shouldn't. You have Office or PDF viewers (OK, granted, PDF ssems to be inside browsers now...) to view your data files.
If you want to show a preview in the browser, you have to upload it first and store it in a "for-preview" dir or something. When OK, move it to its final destination, otherwise, delete.
The File API will allow you to read the data from the file, but then you have the trouble of parsing it and rendering it. Mozilla have released a JavaScript PDF viewer, but I'm not aware of anything for MS Office files.
Back in the days you were able to do something like that:
<object data="word.doc">You do not have Word installed on your machine</object>
Not sure if this is still supported, but if so, you could use JS to inject that object onto the page to preview it.
Ajax upload your file,then after uploaded return path name and preview it.
blueimp's jQuery-File-Upload was great for me.
you can view its basic plugin.
https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin
You can do it with pdf, here is the tutorial:
https://usefulangle.com/post/87/javascript-preview-pdf-during-upload
Don't know if it is possible for doc/docx
You can do it using this web component: https://avipunes.github.io/file-viewer/
This web component under the hood uses some microsoft embedding endpoint:
https://view.officeapps.live.com/op/embed.aspx?src=${fileURI}
you can see an example here:
https://view.officeapps.live.com/op/embed.aspx?src=https://file-examples-com.github.io/uploads/2017/02/file_example_XLS_10.xls
I want to load data from this text file that is in the same folder as the html file on my computer but it won't work. In process of learning Ajax and put together this little test for myself test.html and the text file test.txt. Any advice please, would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script>
function loadData()
{
var test;
test=new XMLHttpRequest();
test.onreadystatechange=function()
{
if (test.readyState==4 && test.status==200)
{
document.getElementById("test").innerHTML=test.responseText;
}
}
test.open("GET","test.txt",true);
test.send();
}
</script>
</head>
<body>
<div id="test"></div>
<button type="button" onclick="loadData()">Get data</button>
</body>
</html>
When I press the button, nothing happens. On the site where I saw a similar example the data from the text file is displayed above the button.
The problem is likely to be that you're accessing the files directly on your local system; web browsers have been designed not to allow this in order to prevent saved web pages loading personal files from your disks and uploading them to remote servers. In order to make it work, you'll need to run a web server locally and use that to view the files. I recommend the Apache web server, which is flexible and can be used on Windows, Linux or OSX.