I just started working on my school assignment with some regular expressions in Javascript. I can't seem to figure out how to actually read data from a text file into variable using jQuery method .get(). When I try my code out nothing happens. It seems like it never enters .get() section. Here is my code:
JS file:
document.getElementById('file').onchange = function(){
var file = "New Text Document.txt"; //this will later be the selected file
$.get(file,function(data){
var myVar = data;
$("#123").html(myVar);
});
};
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>animacija</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript" src="func.js"></script>
<div id="123"></div>
</body>
</html>
The code snippet seems to be ok, but it will not work locally since $.get is for ajax requests and requires full available server path.
I rather recommend you the use of FileReader API.
HTML
<title>animacija</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<input type="file" name="file" id="file">
<div id="123"></div>
</body>
JavaScript
document.getElementById('file').onchange = function() {
var file = this.files[0];
var FR = new FileReader();
FR.readAsText(file);
FR.onload = function(data) {
var myVar = data.target.result;
$("#123").html(myVar);
}
};
JSFiddle
Hope it works for you!
Most browsers will not allow file: resources to read other local files. This is to prevent attacks where a downloaded HTML document could start reading (and transmitting) the contents of your hard drive (or at least your Downloads folder) as soon as you open it.
The other thing you need to know here is that $.get is used for getting resources from an HTTP server, while file inputs are used to allow a user to select a file from their local drive. I realize in your case it's a little confusing, because your web page is on your local hard drive, but imagine if your HTML and scripts were being hosted online, and some other user (not you) was using them to process their own locally-stored files.
MDN has a good tutorial on how to get started with <input type="file"> inputs.
The code won't work locally due to cross-origin limitations.
It works fine when run on a remote server and all files are in the same folder.
If you want to read local files (aka. files selected by user through the file input) you can read more about FileAPI here:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
Related
I have an application that generates JSON-based documents. For complicated reasons, the output of that application is often imperfect and needs minor manual corrections. We wrote a validator to detect cases where manual corrections may be needed; users can then choose whether or not to make them. The validator was written as a simple HTML+JS page that users clone from git and load from a file: URL.
Here is a simplified version of the validator, omitting all of the UI, error handling, and data parsing logic:
function loadFile() {
var filePath;
var reader;
document.getElementById("validation_output").innerHTML = "";
filePath = document.getElementById("fileinput");
reader = new FileReader();
reader.onload = receivedText;
reader.readAsArrayBuffer(filePath.files[0]);
}
function receivedText(e) {
document.getElementById("validation_output").textContent = "Successfully read from file!";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<input type="file" id="fileinput">
<input type="button" value="Validate File" onclick="loadFile()">
</div>
<div id="validation_output">
</div>
</body>
</html>
In normal use, a user uses the file input to select a file, then clicks "Validate" to run the validation. If the file fails validation, then the user makes edits to the file out of band, then clicks "Validate" again to see if the changes corrected the problems.
The problem is that while the validator works on the initial validation pass, it fails on the second pass if the file changed. The browser doesn't throw an exception or log an error to the console; it just never makes the onload callback. This only happens if the contents of the file change; if I re-validate an unchanged document, then it works as expected. The only work-around that I've identified is to re-load the page and use the file input to select the file again.
How can I make the validator re-load the input file on the second pass?
There seems to be no way around the limitations of FileReader (like its problems to access a chosen file after it has changed).
Solution:
The majority of current browsers (except Firefox) now supports the new File System Access API.
Here is an example on how to use it with changing files.
Unfortunately you will NOT be able to RUN this snippet within Stackoverflow, because showOpenFilePicker() is not allowed in sandboxed documents.
<!DOCTYPE html>
<html>
<head>
<script>
let fileHandle;
async function selectFile() {
[fileHandle] = await window.showOpenFilePicker();
let filenameDiv = document.getElementById('filenameDiv');
filenameDiv.innerHTML = fileHandle.name;
readFile();
};
async function readFile() {
const file = await fileHandle.getFile();
const contents = await file.text();
let outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = contents;
}
</script>
</head>
<body>
<div style="margin: 20px;">
<p><button onclick="selectFile()">Choose template file</button></p>
<p><button onclick="readFile()">Reload</button></p>
<div id="filenameDiv" style="background: #fff;"></div>
</div>
<div id="outputDiv" style="background: #fff; min-height: 100px;"></div>
</body>
</html>
I have this code which will display the file name after file has been selected:
<input id="file-input" type="file" />
<script>
const fileInput = document.querySelector('#file-input');
fileInput.onchange = function(){
console.log('file name:', this.value)
}
</script>
I prepared two windows shortcut file (produced by Desktop ---> right click ---> new ---> shortcut)
the first shortcut file
the target is https://www.baidu.com/ and the file name is www.baidu.com
after i select this file, the output is C:\fakepath\www.baidu.com.url in callback, which is working as expected
the second shortcut file
target is https://www.google.com/ and the file name is www.google.com
but after select this file, i expect it to output C:\fakepath\www.google.com.url in callback, but it outputs something like C:\fakepath\TQCJEVEM
Why is this happening?
Disclaimer: I'm still not sure about the why, but I can make a guess about what is happening.
When you create a windows shortcut (like you mentioned above) where the target is a Network Resource, it creates a URL file that has a .url extension.
NOTE: Microsoft Windows does not display the ".url" file extension even though it exists in the filename. Therefore, URL files saved using Windows web browsers will appear with only the filename prefix.
A URL file on windows looks something like this:
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,11
[InternetShortcut]
IDList=
URL=https://www.baidu.com/
HotKey=0
When you upload the baidu shortcut, windows simply uploads the file with above content.
HOWEVER
When you upload the google shortcut, windows actually downloads a copy of the www.google.com website landing page, stores it in the local cache somewhere in the ..\AppData\Local\Microsoft\Windows\INetCache\.. folder and then uploads that cache file which could have its filename as a randomly generated string. Every new attempt would generate a new string for filename.
Hope this points you in the right direction.
Edit:
To verify the content of the uploaded file, slightly modify your code using sample code from this answer.
function init() {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event) {
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});
i'm trying to make cloudinary direct upload working but something in the documentation is missing... here are the steps i'm doing:
Controller:
/**
* MyaccountController
*
* #description :: Server-side logic for managing myaccounts
* #help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'MyCloudName',
api_key: 'MyAPIKey',
api_secret: 'MyAPISecret'
});
Now this is my layout:
<!--SCRIPTS-->
<script type="text/javascript" src="/js/dependencies/sails.io.js"></script>
<script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="/js/jquery.cloudinary.js"></script>
<script src="../node_modules/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
<script type="text/javascript">
cloudinary.cloudinary_js_config();
var cloudinary_cors = "http://" + window.location.host + "/cloudinary_cors.html";
console.log(cloudinary_cors);
cloudinary.uploader.image_upload_tag('photo', { callback: cloudinary_cors });
$(".photo").cloudinary_fileupload();
// Using the config function
var cl = cloudinary.Cloudinary.new();
cl.config( "MyCloudName", "MyAPIKey");
/*
$.cloudinary.config({ cloud_name: 'MyCloudName', api_key: 'MyAPIKey'});
</script>
My form:
<form action="" method="post" enctype="multipart/form-data" class="upload_form">
<div class="form-group">
<label>Foto de perfil</label>
<input type="file" name="photo" id="photo" class="photo">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Cargar</button>
</div>
</form>
I don't get why it isn't working, in the docs it says Cloudinary's jQuery plugin requires your cloud_name and additional configuration parameters to be available. Note: never expose your api_secret in public client side code.
To automatically set-up Cloudinary's configuration, include the following line in your view or layout:
cloudinary.cloudinary_js_config()
This is done...
Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequestâ) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.
This solution requires placing cloudinary_cors.html in the static folder of your Node application. This file is available in the html folder of Cloudinary's Javascript library. The following code builds a URL of the local cloudinary_cors.html file:
Done...
Direct upload file tag
Embed a file input tag in your HTML pages using the image_upload_tag view helper method.
The following example adds a file input field to your form. Selecting or dragging a file to this input field will automatically initiate uploading from the browser to Cloudinary.
cloudinary.uploader.image_upload_tag('image_id', { callback: cloudinary_cors });
this is what i don't get... this is the uploader? how should i use it? and then i don't know what else to do, i'm using different docs to make it work but nothing helps... I hope anyone who did this can help me, thanks!
On controller initialize cloudinary as
var uploader = cloudinary.uploader.image_upload_tag('image_id', { callback: cloudinary_cors, html: { multiple: 1 } });
and pass it to view and render it over there,
<%-uploader%>
then use jquery to get data:
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {}
you can use this script to bind the data to some hidden fields inside your form and
cloudinary-fileupload will be generated when <%-uploader%> is rendered
In addition to CodeBean's answer, note that it seems that there are different ways of using Cloudinary that are mixed here (in the original code as was in question).
Controller
As far as it can be seen from here, the MyaccountController controller doesn't do a thing:
You're requiring "cloudinary" - presumably from npm install, which creates an instance of the jQueryless Cloudinary class.
The variable is local to the controller so has no effect on the rest of the code
View:
Only one of these lines is required (preferably the second one):
<script type="text/javascript" src="/js/jquery.cloudinary.js"></script>
<script src="../node_modules/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
This method returns a string with the <script> tag. The string should be then embedded in the HTML code. It is a server side code.
Here, it does nothing.
cloudinary.cloudinary_js_config();
If you're using the jQuery File Upload code, you should refer to $.cloudinary. cloudinary was never defined in your layout.
Now you're creating a jQueryless instance, which you don't use afterwards.
var cl = cloudinary.Cloudinary.new();
cl.config( "MyCloudName", "MyAPIKey");
Finally, there's an open-ended comment with the code you were supposed to use in the beginning of the whole script:
/*
$.cloudinary.config({ cloud_name: 'MyCloudName', api_key: 'MyAPIKey'});
Regardless of CodeBean's response, you still need to config $.cloudinary.
I am required to remotely include into my appcelerator project, a javascript file available at a particular link, and use the function declared in that file to process some data.
What i would like to achieve is something like the following in html -
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod(localdata);
});
//use testVariable as necessary
</script>
//someMethod() is declared in remotely available Data.js
I am a newb at Appcelerator and im not really able to follow some of the threads i have come across, so some detailed help would be really appreciated. Thank you in advance.
Well according to me , you should first understand few points first :
You want to include a remote file hosted at some server , now as the Titanium code converts to native code at compile time , you cannot include Titanium API's from remote file.
If you want to include a remote file , then only option which I see is loading that file in webview.
Now coming to your problem , as you said that you want to fetch some data only from remote server by triggering some JS function from remote file. So following is what would I do :-
a/ Create a hidden webview in my main window with a EventListener of webview. Something like :
var webview = Titanium.UI.createWebView({url:'localHtmlFile.html'});
//event listener to handle the response from webview
Ti.App.addEventListener('fromWebView', function(e)
{
var testVariable = e.data;
});
b/ In localHtmlFile.html file :
<!DOCTYPE html>
<html>
<body>
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod();
//respond the fetch data to the main window via fireEvent
Ti.App.fireEvent( 'fromWebView', { data : testVariable } );
});
</script>
</body>
</html>
PS : This is just a logic to begin with , you have to edit code according to your requirements