I want dropped text files to be shown by their contents or their complete location so that I can load contents of that location into the "drop_zone".
This is what I have till now. I was just able to access the file name:
<html>
<head>
<title></title>
</head>
<body>
<textarea id="drop_zone">Drop files here</textarea>
<output id="list"></output>
<script>
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
document.getElementById('drop_zone').innerHTML = files[0].name;
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
</body>
</html>
here is the final code :
<html>
<head>
<title></title>
</head>
<body>
<textarea id="drop_zone">Drop files here</textarea>
<script>
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
var reader = new FileReader();
reader.onload = function(event) {
document.getElementById('drop_zone').value = event.target.result;
}
reader.readAsText(files[0],"UTF-8");
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
</body>
</html>
http://www.html5rocks.com/en/tutorials/file/dndfiles/ should be a good resource. You need to use a FileReader to read the contents of the file as a String.
Due to security limits, a page isn't able to load contents of files without something like a Java applet set up with appropriate permissions; and, even then, it's not too possible.
However, that isn't to say it's impossible; simply upload the file to a server and echo the contents back out to the browser. That is how many text-editing-type web applications function.
How you implement this is up to you.
Further, as Maz has pointed out, you can also use built-in APIs to aid you in doing what you're trying to do. Do note, however, this solution is not necessarily cross-browser compatible.
Related
I cannot open the uploaded file and I strictly follow Google Guide's instruction:
Google Guide
which are
//under Basic interact.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function processForm(formObject) {
var formBlob = formObject.myFile;
var driveFile = DriveApp.createFile(formBlob);
return driveFile.getUrl();
}
AND
//under index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
}
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Got it!';
}
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input name="myFile" type="file" />
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
I can upload the file (say photo.jpg with 5kb) using the index.html.
After the uploading, I could find (photo.jpg with 8kb) in https://drive.google.com/drive/my-drive.
However, I cannot open the file (photo.jpg with 8kb) by previewing in Google Drive or by opening the file after downloading. (Error message: Paint cannot read this file. This is not a valid bitmap file, or its format is not currently supported)
The same problem when I tried a docx file. (Before upload: 45kb) (After upload: 79kb) (Error message#1: Word found unreadable content. Do you want to recover the contents of this document?)(After pressing Yes: Word experienced an error trying to open the file. Try these suggestions. Blablabla)
I do not know what to do next when I strictly follow the Google Guide.
Please help me..I am new to everything.Thank you.
And sorry for my poor english T^T
<button onclick="hoge()">hoge</button>
<script>
function hoge(){
if(es){
es.close()
}
var es = new EventSource('/hoge')
es.onmessage = function(e) {
console.log(e)
}
}
</script>
I want to save resources, so it clicked and start connect EventSource.
The new connection start each time clicked, so I want to disconnect the previous connection.
I tried the above code but it didn't work. How should I do please.
You don't have the actual scope of the first EventSource when you call the function the second time, so the variable es is empty for you even though you have an EventSource already instantiated.
I am not sure why do you close and recreate the EventSource in the first place, but here is a solution for your exact problem:
Try this:
<script>
var eventSource;
function hoge(){
if(eventSource){
eventSource.close()
}
eventSource = new EventSource('/hoge')
eventSource.onmessage = function(e) {
console.log(e)
}
}
</script>
Have in mind that the eventSource is located in the global scope(or in other words, it is directly attached to the window object in the context of a browser) this way, so you might want to wrap the whole code in a module or at least in another function. In short, use this:
<script>
(function() {
var eventSource;
function hoge(){
if(eventSource){
eventSource.close()
}
eventSource = new EventSource('/hoge')
eventSource.onmessage = function(e) {
console.log(e)
}
}
})();
</script>
I'm trying to write a polling web app that checks Google Drive and automatically downloads files without user interaction.
Using ContentService I have managed to get things working when I place the code in the doGet function.
However this only works once and there does not appear to be a way to refresh or reload the page automatically on a timer event.
Using a SetTimeout on the client side javascript I can get a function on the server side to automatically trigger at certain intervals but then I am stuck with what to do with the output from ContentService.
The on Success call back will not accept the output from createTextOutput.
My solution does not not need to be deployed and I'm happy to execute from the editor if that expands my choices.
So once I have the output from createTextOutput on my server side what am I supposed to do with it to get it back to the client in order to cause the file download?
I have included the code if that helps.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
setTimeout(
function ()
{
document.getElementById('results').innerHTML = 'Event Timer';
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailure)
.fetchFromGoogleDrive();
}, 60000);
function onSuccess(sHTML)
{
document.getElementById('results').innerHTML = 'File Downloaded ' + sHTML;
}
function onFailure(error)
{
document.getElementById('results').innerHTML = error.message;
}
</script>
</head>
<body>
<div id="results">Waiting to DownLoad!</div>
id="Fetch">Fetch!</button>
</body>
</html>
function doGet() {
Logger.log('doGet');
return HtmlService.createHtmlOutputFromFile('form.html');
}
function fetchFromGoogleDrive() {
//Logger.Log('fetchFromGoogleDrive');
var fileslist = DriveApp.searchFiles("Title contains 'Expected File'");
if (fileslist.hasNext()) {
//Logger.Log('File found');
var afile = fileslist.next();
var aname = afile.getName();
var acontent = afile.getAs('text/plain').getDataAsString();
var output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.CSV);
output.setContent(acontent);
output.downloadAsFile(aname);
return afile.getDownloadUrl();
}
else
{
//Logger.Log('No File Found');
return 'Nothing to download';
}
//Logger.log('All files processed.');
}
EDIT: Different answer after clarification.
If this is intended to run automated as a webapp what I would do is return the getDownloadUrl and create a new iFrame using that that as the source.
Apps Script
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function getDownloadLink(){
//slice removes last parameter gd=true. This needs to be removed. slice is a hack you should do something better
return DriveApp.getFileById("0B_j9_-NbJQQDckwxMHBzeVVuMHc").getDownloadUrl().slice(0,-8);
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<p id="dlBox"></p>
</body>
<script>
function buildLink(res){
var dlBox = document.createElement("iframe");
dlBox.src = res;
document.getElementById("dlBox").appendChild(dlBox)
}
//automate this as you need
google.script.run
.withSuccessHandler(buildLink)
.getDownloadLink();
</script>
</html>
I was performing some tests with the WebAudio API in iOS6. It seems that when you click on a button, the AudioBufferSourceNode will be created correctly and connected to the Contexts destination.
I was simply wondering if there was any way of playing a sound automatically when a page is loaded, as iOS6 devices seem to build the SourceNode correctly, but no sound comes out.
I have posted my code below:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML 5 WebAudio API Tests</title>
<script type="text/javascript">
var audioContext,
audioBuffer;
function init() {
try {
audioContext = new webkitAudioContext();
initBuffer('resources/dogBarking.mp3');
} catch(e) {
console.error('webkitAudioContext is not supported in this browser');
}
}
function initBuffer(desiredUrl) {
var url = desiredUrl || '';
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
audioBuffer = buffer;
}, onError);
}
request.send();
}
function playSound(startTime, endTime) {
var audioSource = audioContext.createBufferSource();
audioSource.buffer = audioBuffer;
audioSource.connect(audioContext.destination);
audioSource.noteOn(0);
audioSource.noteOff(10);
}
</script>
</head>
<body onload="init()">
<script type="text/javascript">
(function() {
var buttonNode = document.createElement('input');
buttonNode.setAttribute('type', 'button');
buttonNode.setAttribute('name', 'playButton');
buttonNode.setAttribute('onclick', 'playSound(0, 1)')
buttonNode.setAttribute('value', 'playSound()');
document.body.appendChild(buttonNode);
document.write('<a id="test" onclick="playSound(0, 2)">hello</a>');
var testLink = document.getElementById('test');
var dispatch = document.createEvent('HTMLEvents');
dispatch.initEvent("click", true, true);
testLink.dispatchEvent(dispatch);
}());
</script>
</body>
</html>
I hope this makes sense.
Kind regards,
Jamie.
This question is very similar to No sound on iOS 6 Web Audio API . WebAudio API needs user input to be initialized and after first sound plays in this way WebAudioAPI works greatly without any actions needed during current session.
You can initialize API by adding listener to first window touchstart event, like this:
w.addEventListener('touchstart', myFunctionThatPlaysAnyWebAudioSound);
How to wait till onload event completes
function(){
var filedata=null;
reader.onload=function(e){
filedata=e.target.result;
};
reader.readAsBinaryString(file);
//I need code to wait till onload event handler gets completed.
return filedata;
}
Typical solution to this is to separate your code so, that the part which uses the loaded data is in a separate function, which is then called from the event.
Pseudo-code'ish:
function load() {
//load here
reader.onload = function(e) {
process(e.target.result);
}
}
function process(result) {
//finish working here
}
You can read synchronously using threads (Webworkers in Javascript).
http://www.w3.org/TR/FileAPI/#readingOnThreads
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<form><input type="file" id="files" name="file" onchange="upload()" /></form>
function readFile(dfd) {
bytes = [];
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var content = evt.target.result;
//bytes = stringToBytes(content);
dfd.resolve(content);
}
};
reader.readAsBinaryString(file);
}
function upload() {
var dfd = new $.Deferred();
readFile(dfd);
dfd.done(function(content){
alert("content:" + content);
});
}
The answer by Jani is correct, but in the case of dropping multiple files at once in a droparea, there are not separate events for each file (as far as I know). But the idea may be used to load the files synchronously by recursion.
In the code below I load at number of files and concatenate their content into a single string for further proccesing.
var txt="", files=[];
function FileSelectHandler(e) {
e.preventDefault();
files = e.target.files || e.dataTransfer.files;
txt="";
readFile(0);
}
function readFile(n) {
file=files[n];
var reader = new FileReader();
reader.onload = function() {
txt += reader.result;
}
reader.readAsText(file);
if (n<files.length-1) { readFile(n+1); }
else { setTimeout(doWhatEver, 100);}
}
function doWhatEver(){
outtext.innerHTML=txt;
}
The last file also needs a bit of extra time to load. Hence the "setTimeout".
"outtext" is the handle to a textarea where the entire string is displayed. When outputting in at textarea the browser wont' parse the string. This makes it possible to view not only text but also html, xml etc.
No there is not. All IO operations must be asynchronous in Javascript.
Making file operation synchronous would effectively block the browser UI thread freezing the browser. The users don't like that.
Instead you need to design your script in asynchronous manner. It is quite easy with Javascript.