Auto record and allow to play once using JQuery - javascript

Hiii Everyone,
Below is the sample code for record.
<html>
<body>
<audio controls autoplay></audio>
<input onclick="startRecording()" type="button" value="start recording" />
<input onclick="stopRecording()" type="button" value="stop recording and play" />
<script>
var onFail = function(e) {
console.log('Rejected!', e);
};
var onSuccess = function(s) {
stream = s;
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var stream;
var audio = document.querySelector('audio');
function startRecording() {
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
audio.src = window.URL.createObjectURL(stream);
}
</script>
</body>
</html>
What I want to do is setInterval for 40 secs it will buffer for 40 secs like recording will start in 40secs timer will run after 40 secs it will show the play button to check audio recorded.Below I had added sample screenshots
Progress bar will show the recording..Similarly there will be some question with audio there I need to start recording once audio complete play.If anybody knows solution for this issue Please help me.Thanks for ur support

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<style>
.center_div {
width: 500px;
height: 100px;
background-color: #f5f5f5;
border: 1px solid #808080;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
/* half width*/
margin-top: -50px;
/* half height*/
padding: 25px;
}
.recording_label {
display: block;
text-align: center;
padding: 10px;
font-family: sans-serif;
font-size: 1.1em;
margin-bottom: 25px;
}
.loader_bg {
min-width: 100%;
background: #c5c5c5;
min-height: 20px;
display: block;
}
.loader_bg1 {
min-width: 90%;
background: grey;
min-height: 20px;
display: inline-block;
position: relative;
top: -20px;
}
</style>
</head>
<body>
<audio controls autoplay></audio>
<input onclick="startRecording();" type="button" value="start recording" />
<input onclick="stopRecording();" type="button" value="stop recording and play" />
<div class="center_div">
<span class="recording_label">Please wait...</span>
<span class="loader_bg"></span>
<span class="loader_bg1"></span>
</div>
<script>
var onFail = function(e) {
console.log('Rejected!', e);
};
var onSuccess = function(s) {
stream = s;
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var stream;
var audio = document.querySelector('audio');
function startRecording() {
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
audio.src = window.URL.createObjectURL(stream);
}
$(function() {
var max = 40;
var count = max + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording...");
$('.loader_bg1').css({
'min-width': '' + (100) + '%'
})
startRecording();
recordingSec(40);
return;
}
$(".recording_label").html("Recording will begin in " + count + " sec.");
var percent = (count / max) * 100;
$('.loader_bg1').css({
'min-width': '' + (100 - percent) + '%'
})
}
});
function recordingSec(sec) {
var count = sec + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording stopped...Playing");
$('.loader_bg1').css({
'min-width': '' + (100) + '%'
})
stopRecording();
return;
}
$(".recording_label").html("Recording started [ " + (sec - count) + " / " + sec + " ] sec.");
var percent = (count / sec) * 100;
$('.loader_bg1').css({
'min-width': '' + (100 - percent) + '%'
})
}
}
</script>
</body>
</html>

Try To Use:
.btn-primary-success {
color: #fff;
background-color: #04b5e0;
border-color: #04b5e0;
}
.btn-primary-success:hover, .btn-primary-success:focus, .btn-primary-success:active, .btn-primary-success.active, .open .dropdown-toggle.btn-primary-success {
color: #fff;
background-color: #09a0c5;
border-color: #09a0c5;
}
Using Html Code:
<div style="text-align: left; padding: 10px;">
<label style="margin-right: 10px; font-size: 14px !important;">Dictate Status</label>
<a class="btn btn-primary-success pauseAudioDocWS pause" title="Pause" style="display: none; margin-right: 5px;"
data-value="">
<i class="imgpauseWS fa fa-lg fa-pause" style="cursor: pointer; margin: 2px 5px;"></i>
<b class="ppauseWS btn-primary-success">Pause</b></a>
<a class="btn btn-primary-success recordAudioDocWS inActiveWS" title="Start" style="margin-right: 20px;"
data-value="">
<b class="pplayWS">Click here to Start</b>
<i class="imgplayWS fa fa-lg fa-microphone" style="cursor: pointer; margin: 2px 5px;"></i>
</a>
<span class="stopwatchWS" style="display: none; margin-right: 10px;">00:00:00</span>
</div>
Download Audio and Timer File in github links:
https://github.com/fezalhalai/AudioRecorder.js
Using Jquery Code:
<script src="../js/StopTimer.js"></script>
<script src="../js/jquery.timer.js"></script>
<script src="../js/AudioRecorder.js"></script>
<script src="https://cdn.webrtc-experiment.com/RecordRTC.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/gif-recorder.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/gumadapter.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/DetectRTC.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function () {
var oldRecorderWS;
$('.recordAudioDocWS').click(function () {
var $this = $(this);
if (oldRecorderWS != undefined) {
if (oldRecorderWS != document.tmId) {
alert('Dictating Already In Progress, Please Stop Previous Dictating To Continue');
return;
}
}
var checkin_id = document.tmId;
localStorage.setItem('checkin_id', checkin_id);
localStorage.setItem('Tran_Type', 'W');
oldRecorderWS = document.tmId;
var roomId = document.tmId;
localStorage.setItem('roomId', roomId);
var isRecording = false;
$(".isActiveWS").each(function () {
if ($(this).hasClass('isActiveWS')) {
isRecording = true;
}
});
if (isRecording == true) {
document.isRecordActivityPerforms = true;
if (confirm('Dictating in progress do you want to stop and save?')) {
oldRecorderWS = undefined;
$this.next('span').css('display', 'none');
Example1.resetStopwatch();
$('.stoprecmessage').css('display', 'block');
$(".isActiveWS").each(function () {
$(this).addClass('inActiveWS');
$(this).removeClass('isActiveWS');
$(this).find('.pplayWS').text('Click here to Start');
//$(this).find('.imgplay').attr('src', 'img/play.png');
$(this).find('.imgplayWS').addClass('fa-stop');
$(this).find('.imgplayWS').addClass('fa-microphone');
$(this).attr('title', 'Start');
});
//$('.tbothers').css('pointer-events', 'auto');
$('.btn-ws-next').removeAttr('disabled', '');
$('.btn-ws-prv').removeAttr('disabled', '');
$this.prev('a').css('display', 'none');
$this.prev('a').addClass('pause');
StartRecording();
document.isRecordActivityPerform = false;
//$this.next().next('img').removeClass('hidden');
if ($(CurruntAudioRecRow).parent().parent().find('.hdtmvid').val() == document.tmId) {
$(CurruntAudioRecRow).parent().parent().find('td .audioList').removeClass();
$(CurruntAudioRecRow).parent().parent().find('td .REC').removeClass('hidden');
$(CurruntAudioRecRow).parent().parent().find('td .PEN').addClass('hidden');
}
}
}
else {
$('.btn-ws-next').attr('disabled', 'disabled');
$('.btn-ws-prv').attr('disabled', 'disabled');
document.isRecordActivityPerform = true;
$this.next('span').css('display', 'inline');
$this.next().next('img').addClass('hidden');
Example1.init($this.next('span'));
Example1.resetStopwatch();
Example1.Timer.toggle();
$this.removeClass('inActiveWS');
$this.addClass('isActiveWS');
$this.find('.pplayWS').text('Stop');
//$this.find('.imgplay').attr('src', 'img/stop.png');
$this.find('.imgplayWS').removeClass('fa-microphone');
$this.find('.imgplayWS').addClass('fa-stop');
$this.attr('title', 'Stop');
$this.prev('a').css('display', 'inline-table');
StartRecording();
}
});
$('.pauseAudioDocWS').click(function () {
document.isRecordActivityPerform = true;
var $this = $(this);
Example1.Timer.toggle();
var btnStartRecording = document.querySelector('#btn-start-recording');
if ($(this).hasClass('pause')) {
btnStartRecording.recordRTC.pauseRecording();
recordingPlayer.pause();
$(this).addClass('resume');
$(this).removeClass('pause');
$(this).find('.ppauseWS').text('Resume');
//$(this).find('.imgpause').attr('src', 'img/play.png');
$(this).find('.imgpauseWS').removeClass('fa-pause');
$(this).find('.imgpauseWS').addClass('fa-microphone');
$(this).attr('title', 'Resume');
$(this).next('a').css('pointer-events', 'none');
$(this).next('a').attr('disabled', 'disabled');
}
else if ($(this).hasClass('resume')) {
btnStartRecording.recordRTC.resumeRecording();
recordingPlayer.play();
$(this).addClass('pause');
$(this).removeClass('resume');
$(this).find('.ppauseWS').text('Pause');
//$(this).find('.imgpause').attr('src', 'img/pause.png');
$(this).find('.imgpauseWS').removeClass('fa-microphone');
$(this).find('.imgpauseWS').addClass('fa-pause');
$(this).attr('title', 'Pause');
$(this).next('a').css('pointer-events', 'auto');
$(this).next('a').removeAttr('disabled');
}
});
});
</script>

Related

How To Upload Multiple Files To Google Drive With Apps Script [duplicate]

I'm trying to upload multiple files at once with my app. It recognizes when there are 2 or more files being selected. However, it will only upload the 1st file that is selected to my drive. Also (although quite minor), I was wondering how I can change my textarea font to be Times New Roman to stay consistent with the rest of the font.
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('form')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFiles(form) {
try {
var foldertitle = form.zone + ' | Building: ' + form.building + ' | ' + form.propertyAddress + ' | ' + form.attachType;
var folder, folders = DriveApp.getFolderById("0B7UEz7SKB72HfmNmNnlSM2NDTVVUSlloa1hZeVI0VEJuZUhSTmc4UXYwZjV1eWM5YXJPaGs");
var createfolder = folders.createFolder(foldertitle);
folder = createfolder;
var blob = form.filename;
var file = folder.createFile(blob);
file.setDescription(" " + form.fileText);
return "File(s) uploaded successfully! Here is the link to your file(s): " + folder.getUrl();
} catch (error) {
Logger.log('err: ' + error.toString());
return error.toString();
}
}
function uploadArquivoParaDrive(base64Data, nomeArq, idPasta) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(nomeArq);
var file = DriveApp.getFolderById("0B7UEz7SKB72HfmNmNnlSM2NDTVVUSlloa1hZeVI0VEJuZUhSTmc4UXYwZjV1eWM5YXJPaGs").createFile(ss);
return file.getName();
}catch(e){
return 'Erro: ' + e.toString();
}
}
form.html
<body>
<div id="formcontainer">
<label for="myForm">Facilities Project Database Attachment Uploader:</label>
<br><br>
<form id="myForm">
<label for="myForm">Project Details:</label>
<div>
<input type="text" name="zone" placeholder="Zone:">
</div>
<div>
<input type="text" name="building" placeholder="Building(s):">
</div>
<div>
<input type="text" name="propertyAddress" placeholder="Property Address:">
</div>
<div>
<label for="fileText">Project Description:</label>
<TEXTAREA name="projectDescription"
placeholder="Describe your attachment(s) here:"
style ="width:400px; height:200px;"
></TEXTAREA>
</div>
<br>
<label for="attachType">Choose Attachment Type:</label>
<br>
<select name="attachType">
<option value="Pictures Only">Picture(s)</option>
<option value="Proposals Only">Proposal(s)</option>
<option value="Pictures & Proposals">All</option>
</select>
<br>
<label for="myFile">Upload Attachment(s):</label>
<br>
<input type="file" name="filename" id="myFile" multiple>
<input type="submit" value="Submit" onclick="iteratorFileUpload()">
</form>
</div>
<div id="output"></div>
<script>
function iteratorFileUpload() {
var allFiles = document.getElementById('myFile').files;
if (allFiles.length == 0) {
alert('No file selected!');
} else {
// Send each file one at a time
var i=0;
for (i=0; i < allFiles.total; i+=1) {
console.log('This iteration: ' + i);
sendFileToDrive(allFiles[i]);
};
};
};
function sendFileToDrive(file) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
google.script.run
.withSuccessHandler(fileUploaded)
.uploadArquivoParaDrive(content, file.name, currFolder);
}
reader.readAsDataURL(file);
};
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
// Upload de arquivo dentro das pastas Arquivos Auxiliares
function iterarArquivosUpload() {
var arquivos = document.getElementById('inputUpload').files;
if (arquivos.length == 0) {
alert('No file selected!');
} else {
//Show Progress Bar
numUploads.total = arquivos.length;
$('.progressUpload').progressbar({
value : false
});
$('.labelProgressUpload').html('Preparando arquivos para upload');
// Send each file at a time
for (var arqs = 0; arqs < numUploads.total; arqs++) {
console.log(arqs);
enviarArquivoParaDrive(arquivos[arqs]);
}
}
}
function enviarArquivoParaDrive(arquivo) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + arquivo.name);
google.script.run.withSuccessHandler(updateProgressbar).uploadArquivoParaDrive(content, arquivo.name, currFolder);
}
reader.readAsDataURL(arquivo);
}
function updateProgressbar( idUpdate ){
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total)*100);
$('.progressUpload').progressbar({value: porc });
$('.labelProgressUpload').html(numUploads.done +'/'+ numUploads.total);
if( numUploads.done == numUploads.total ){
uploadsFinished();
numUploads.done = 0;
};
}
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
body {
max-width: 400px;
padding: 20px;
margin: auto;
}
input {
display: inline-block;
width: 100%;
padding: 5px 0px 5px 5px;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌​ -moz-box-sizing: border-box;
box-sizing: border-box;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="submit"] {
width: auto !important;
display: block !important;
}
input[type="file"] {
padding: 5px 0px 15px 0px !important;
}
</style>
</body>
I know this question is old, but after finding it and related ones, I was never able to get the multiple file upload working. So after a lot of banging my head against walls, I wanted to post a full example (.html and .gs) in case anyone in the future is looking for one to get started. This is working when I deploy it right now and will hopefully work for other people out there. Note that I just hardcoded the folder in the drive to use in the code.gs file, but that can be easily changed.
form.html:
<body>
<div id="formcontainer">
<label for="myForm">Facilities Project Database Attachment Uploader:</label>
<br><br>
<form id="myForm">
<label for="myForm">Project Details:</label>
<div>
<input type="text" name="zone" placeholder="Zone:">
</div>
<div>
<input type="text" name="building" placeholder="Building(s):">
</div>
<div>
<input type="text" name="propertyAddress" placeholder="Property Address:">
</div>
<div>
<label for="fileText">Project Description:</label>
<TEXTAREA name="projectDescription"
placeholder="Describe your attachment(s) here:"
style ="width:400px; height:200px;"
></TEXTAREA>
</div>
<br>
<label for="attachType">Choose Attachment Type:</label>
<br>
<select name="attachType">
<option value="Pictures Only">Picture(s)</option>
<option value="Proposals Only">Proposal(s)</option>
<option value="Pictures & Proposals">All</option>
</select>
<br>
<label for="myFile">Upload Attachment(s):</label>
<br>
<input type="file" name="filename" id="myFile" multiple>
<input type="button" value="Submit" onclick="iteratorFileUpload()">
</form>
</div>
<div id="output"></div>
<div id="progressbar">
<div class="progress-label"></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
var allFiles = document.getElementById('myFile').files;
if (allFiles.length == 0) {
alert('No file selected!');
} else {
//Show Progress Bar
numUploads.total = allFiles.length;
$('#progressbar').progressbar({
value : false
});//.append("<div class='caption'>37%</div>");
$(".progress-label").html('Preparing files for upload');
// Send each file at a time
for (var i = 0; i < allFiles.length; i++) {
console.log(i);
sendFileToDrive(allFiles[i]);
}
}
}
function sendFileToDrive(file) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
var currFolder = 'Something';
google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);
}
reader.readAsDataURL(file);
}
function updateProgressbar( idUpdate ){
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total)*100);
$("#progressbar").progressbar({value: porc });
$(".progress-label").text(numUploads.done +'/'+ numUploads.total);
if( numUploads.done == numUploads.total ){
//uploadsFinished();
numUploads.done = 0;
};
}
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
body {
max-width: 400px;
padding: 20px;
margin: auto;
}
input {
display: inline-block;
width: 100%;
padding: 5px 0px 5px 5px;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌​ -moz-box-sizing: border-box;
box-sizing: border-box;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="submit"] {
width: auto !important;
display: block !important;
}
input[type="file"] {
padding: 5px 0px 15px 0px !important;
}
#progressbar{
width: 100%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;
}
.progress-label {
float: left;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
</body>
code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('form')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFileToDrive(base64Data, fileName) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(fileName);
var dropbox = "Something"; // Folder Name
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var file = folder.createFile(ss);
return file.getName();
}catch(e){
return 'Error: ' + e.toString();
}
}
Updated For May 2017
I updated and improved barragan's answer.
Advantages:
Allows users to create a subfolder name to contain all the files uploaded during this session
Ensures that these subfolders all exist within one specified folder within your Google Drive
The page/form is mobile-responsive
You can start with this example just to create the script and get to know the basics.
Then you can completely replace form.html with this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>
Send Files
</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
$(document).ready(function () {
function afterSubfolderCreated(subfolderId) {
console.log(subfolderId);
console.log(allFiles);
numUploads.total = allFiles.length;
$('#progressbar').progressbar({
value: false
});
$(".progress-label").html('Preparing files for upload');
for (var i = 0; i < allFiles.length; i++) {
console.log(i);
sendFileToDrive(allFiles[i], subfolderId);
}
}
function sendFileToDrive(file, subfolderId) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, subfolderId);
}
reader.readAsDataURL(file);
}
function updateProgressbar(idUpdate) {
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total) * 100);
$("#progressbar").progressbar({value: porc});
$(".progress-label").text(numUploads.done + '/' + numUploads.total);
if (numUploads.done == numUploads.total) {
numUploads.done = 0;
$(".progress-label").text($(".progress-label").text() + ': FINISHED!');
$("#progressbar").after('(Optional) Refresh this page if you remembered other screenshots you want to add.');//<a href="javascript:window.top.location.href=window.top.location.href"> does not work
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
var allFiles;
var frm = $('#myForm');
frm.submit(function () {
allFiles = document.getElementById('myFile').files;
if (!frm.checkValidity || frm.checkValidity()) {
if (allFiles.length == 0) {
alert('Error: Please choose at least 1 file to upload.');
return false;
} else {
frm.hide();
var subfolderName = document.getElementById('myName').value;
$.ajax({
url: '',//URL of webhook endpoint for sending a Slack notification
data: {
title: subfolderName + ' is uploading screenshots',
message: ''
}
});
google.script.run.withSuccessHandler(afterSubfolderCreated).createSubfolder(subfolderName);
return false;
}
} else {
alert('Invalid form');
return false;
}
});
});//end docReady
</script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<style>
body {
padding: 20px;
margin: auto;
font-size: 20px;
}
label{
font-weight: bold;
}
input{
font-size: 20px;
padding: 5px;
display: inline-block;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌-moz-box-sizing: border-box;
box-sizing: border-box;
}
.hint{
font-size: 90%;
color: #666;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="file"] {
padding: 5px 0px 15px 0px;
}
#progressbar{
width: 100%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;
}
.progress-label {
float: left;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
li{
padding: 10px;
}
#media only screen and (max-width : 520px) {
#logo {
max-width: 100%;
}
}
</style>
</head>
<body>
<p>
<img src="" id="logo">
</p>
<p>This webpage allows you to send me screenshots of your dating profiles.</p>
<ol>
<li>
In each of your dating apps, take a screenshot (how?) of every part of every page of your profile.
</li>
<li>
Do the same for each of your photos (at full resolution).
</li>
<li>
In the form below, type your first name and last initial (without any spaces or special characters), such as SallyT.
</li>
<li>
Then click the first button and select all of your screenshot images (all at once).
</li>
<li>
Finally, press the last button to send them all to me!
</li>
</ol>
<form id="myForm">
<div>
<label for="myName">Your first name and last initial:</label>
</div>
<div>
<input type="text" name="myName" id="myName" placeholder="SallyT" required pattern="[a-zA-Z]+" value="">
</div>
<div>
<span class="hint">(No spaces or special characters allowed because this will determine your folder name)</span>
</div>
<div style="margin-top: 20px;">
<label for="myFile">Screenshot image files:</label>
<input type="file" name="filename" id="myFile" multiple>
</div>
<div style="margin-top: 20px;">
<input type="submit" value="Send File(s) ➔" >
</div>
</form>
<div id="output"></div>
<div id="progressbar">
<div class="progress-label"></div>
</div>
</body>
</html>
And completely replace server.gs with this:
function doGet() {
var output = HtmlService.createHtmlOutputFromFile('form');
output.addMetaTag('viewport', 'width=device-width, initial-scale=1');// See http://stackoverflow.com/a/42681526/470749
return output.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFileToDrive(base64Data, fileName, subfolderId) {
Logger.log(subfolderId);
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(fileName);
var subfolder = DriveApp.getFolderById(subfolderId);
var file = subfolder.createFile(ss);
Logger.log(file);
return file.getName() + ' at ' + file.getUrl();
} catch(e){
return 'createFile Error: ' + e.toString();
}
}
function createSubfolder(subfolderName){
var dropbox = subfolderName + Utilities.formatDate(new Date(), "US/Eastern", "_yyyy-MM-dd");
Logger.log(dropbox);
var parentFolderId = "{ID such as 0B9iQ20nrMNYAaHZxRjd}";
var parentFolder = DriveApp.getFolderById(parentFolderId);
var folder;
try {
folder = parentFolder.getFoldersByName(dropbox).next();
}
catch(e) {
folder = parentFolder.createFolder(dropbox);
}
Logger.log(folder);
return folder.getId();
}
Joining the pile of older answers, but this really helped me when I implemented my own file multi upload for getting files into Google Drive using the DriveApp V3 api.
I wrote and posted my own solution here: https://github.com/CharlesPlucker/drive-multi-upload/
Improvements:
- Handles multiple files sequentially
- Handles large > 50MB files
- Validation
I wrapped my google api calls into promises since I was running into timing issues when creating a folder and immediately trying to fetch it by name reference. Each one of my promises will only resolve when its file is fully uploaded. To get that working I had to use a Promise Factory. I'll be glad to explain this code if the need arises!
You have to send a file at a time trough the script.run, here's my implementation with FileReaders/ReadAsURL, which makes the file a Base64 string, which can be easily passed around:
Notes:
Dunno if it's necessary but I'm using IFRAME sandbox
I left the progressBar in the code, you can remove it
Everything must be OUTSIDE a form
It accepts any file type
HTML:
// Upload de arquivo dentro das pastas Arquivos Auxiliares
function iterarArquivosUpload() {
var arquivos = document.getElementById('inputUpload').files;
if (arquivos.length == 0) {
alert('No file selected!');
} else {
//Show Progress Bar
numUploads.total = arquivos.length;
$('.progressUpload').progressbar({
value : false
});
$('.labelProgressUpload').html('Preparando arquivos para upload');
// Send each file at a time
for (var arqs = 0; arqs < numUploads.total; arqs++) {
console.log(arqs);
enviarArquivoParaDrive(arquivos[arqs]);
}
}
}
function enviarArquivoParaDrive(arquivo) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + arquivo.name);
google.script.run.withSuccessHandler(updateProgressbar).uploadArquivoParaDrive(content, arquivo.name, currFolder);
}
reader.readAsDataURL(arquivo);
}
function updateProgressbar( idUpdate ){
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total)*100);
$('.progressUpload').progressbar({value: porc });
$('.labelProgressUpload').html(numUploads.done +'/'+ numUploads.total);
if( numUploads.done == numUploads.total ){
uploadsFinished();
numUploads.done = 0;
};
}
Code.GS
function uploadArquivoParaDrive(base64Data, nomeArq, idPasta) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(nomeArq);
var file = DriveApp.getFolderById(idPasta).createFile(ss);
return file.getName();
}catch(e){
return 'Erro: ' + e.toString();
}
}
as #barragan's answer here is the best answer i found after hours and hours of searching for a question many people were asking, i've done a bit of development to improve the design a bit for others as a thanks. still a few bugs and chrome seems to run out of memory and give up with any file over 100MB
here's a live version
server.gs
'function doGet() {
return HtmlService.createHtmlOutputFromFile('form')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFileToDrive(base64Data, fileName) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(fileName);
var dropbox = "Something"; // Folder Name
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var file = folder.createFile(ss);
return file.getName();
}catch(e){
return 'Error: ' + e.toString();
}
}
'
form.html
<head>
<base target="_blank">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Focallocal Uploader</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
<div align="center">
<p><img src="http://news.focallocal.org/wp-content/uploads/2015/03/FOCALLOCAL-Website-Text-Header.png" width="80%"></p>
</div>
</head>
<body>
<div id="formcontainer" width="50%">
<label for="myForm">Focallocal Community G.Drive Uploader</label>
<br>
<br>
<form id="myForm" width="50%">
<label for="myForm">Details</label>
<div>
<input type="text" name="Name" placeholder="your name">
</div>
<div>
<input type="text" name="gathering" placeholder="which fabulous Positive Action you're sending us">
</div>
<div>
<input type="text" name="location" placeholder="the town/village/city and country month brightend by positivity">
</div>
<div>
<input type="text" name="date" placeholder="date of the beautiful action">
</div>
<div width="100%" height="200px">
<label for="fileText">would you like to leave a short quote?</label>
<TEXTAREA name="Quote"
placeholder="many people would love to share in your experience. if you have more than a sentence or two to write, why not writing an article the Community News section of our website?"
></TEXTAREA>
</div>
<br>
<br>
<label for="myFile">Upload Your Files:</label>
<br>
<input type="file" name="filename" id="myFile" multiple>
<input type="button" value="Submit" onclick="iteratorFileUpload();">
</form>
</div>
<div id="output"></div>
<div id="progressbar">
<div class="progress-label"></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
var allFiles = document.getElementById('myFile').files;
if (allFiles.length == 0) {
alert('No file selected!');
} else {
//Show Progress Bar
numUploads.total = allFiles.length;
$('#progressbar').progressbar({
value : false
});//.append("<div class='caption'>37%</div>");
$(".progress-label").html('Preparing files for upload');
// Send each file at a time
for (var i = 0; i < allFiles.length; i++) {
console.log(i);
sendFileToDrive(allFiles[i]);
}
}
}
function sendFileToDrive(file) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
var currFolder = 'Something';
google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);
}
reader.readAsDataURL(file);
}
function updateProgressbar( idUpdate ){
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total)*100);
$("#progressbar").progressbar({value: porc });
$(".progress-label").text(numUploads.done +'/'+ numUploads.total);
if( numUploads.done == numUploads.total ){
//uploadsFinished();
numUploads.done = 0;
};
}
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
body {
max-width: 60%;
padding: 20px;
margin: auto;
}
input {
display: inline-block;
width: 50%;
padding: 5px 0px 5px 5px;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌​ -moz-box-sizing: border-box;
box-sizing: border-box;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="submit"] {
width: auto !important;
display: block !important;
}
input[type="file"] {
padding: 5px 0px 15px 0px !important;
}
#progressbar{
width: 40%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;
}
.progress-label {
float: left;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
</body>
i wasn't able to get the text fields to send an email with the details out, and ran out of time before working out how to hook them up to a Google Spreadsheet, so for the moment they don't record the information added
as an added bonus, it looked fabulous with is in the form.html
<div class="fixed-action-btn horizontal" style="bottom: 45px; right: 24px;">
<a class="btn-floating btn-large red">
<i class="large material-icons">menu</i>
</a>
<ul>
<li><a class="btn-floating red" href="https://focallocal-a-positive-action-movement.myshopify.com/" target="_blank" title="Pimp your Cool at the Positive Action Shop"><i class="material-icons">monetization_on</i></a></li>
<li><a class="btn-floating blue" href="https://www.youtube.com/user/Focallocal" target="_blank" title="Follow the Positive Action Youtube Channel"><i class="material-icons">video_library</i></a></li>
<li><a class="btn-floating green" href="http://focallocal.org/" target="_blank" title="Read our About Us Page"><i class="material-icons">help</i></a></li>
</ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
<script src="https://gumroad.com/js/gumroad.js"></script>
i took it out again as some of the scripts being called in were causing issues. if anyone can fix them it they add a lot to the appearance and functionality of the form
*edit: i've been playing around with it and only around half of the files sent seem to arrive, so there are still some issues with both of the codes here atm

Changing Iframes HTML

I need a script to change the iframes src every certain amount of seconds. The time between the change is different between each one.
Example:
Page Loads
Google.com is loaded.
15 seconds later
Yahoo.com is loaded.
37 seconds later
Ask.com is loaded.
12 seconds later
Dogpile.com is loaded.
and so on and so forth.
I've tried that:
<html>
<head>
<meta charset="utf-8" />
<title>Monitor Presidência</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
</head>
<body>
<div style="width: 100%; display: flex;">
<div class="ui teal progress" data-percent="0" id="example1" style="width: 90%;margin-bottom: 0px">
<div class="bar"></div>
</div>
<div class="ui icon buttons" style="width: 10%">
<button class="ui button" style="width: 25%" onclick="menos_um()">
<i class="left chevron icon"></i>
</button>
<button class="ui button " style="width: 25%" onclick="inicia()">
<i class="play icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="para_aplicacao()">
<i class="pause icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="mais_um()">
<i class="right chevron icon"></i>
</button>
</div>
</div>
<iframe id="envase" class="frame_mon" style="width: 100%;height: 100%;" src="www.google.com.br"></iframe>
<iframe id="frete_hl" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.yahoo.com.br"></iframe>
<iframe id="frete_hl_acum" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.terra.com.br"></iframe>
</body>
<script>
var arr_monitores = ["envase", "frete_hl", "frete_hl_acum"];
var num_monitor = 0;
var progresso = 0;
var myVar;
var setintervalatualizaframe;
function mais_um() {
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";*/
progresso = 100;
myStopFunction();
inicia();
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}*/
};
function menos_um() {
//progresso = 100;
if (num_monitor === 0) {
num_monitor = 2;
} else {
num_monitor--;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";
progresso = 0;
myStopFunction();
inicia();
};
function inicia() {
clearInterval(setintervalatualizaframe);
myStopFunction();
myVar = setInterval(function () {
if (progresso === 100) {
progresso = 0;
if (num_monitor === 2) {
location.reload();
//num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none')
document.getElementById(arr_monitores[num_monitor]).style.display = "";
};
progresso++;
progresso++;
$('#example1').data('percent', progresso);
$('#example1').progress();
}, 3800);
}
function myStopFunction() {
clearInterval(myVar);
//atualiza_frame();
}
inicia();
function para_aplicacao(){
clearInterval(myVar);
atualiza_frame();
}
function atualiza_frame() {
clearInterval(setintervalatualizaframe);
setintervalatualizaframe = setInterval(function () {
document.getElementById(arr_monitores[num_monitor]).src=document.getElementById(arr_monitores[num_monitor]).src;
},1);
}
</script>
</html>
The way you are using setInterval and setTimeout is not properly
handled, as it creates a timer id to schedule execution. 0
A much more efficient way is to use the Promises async library, which is displayed below. 1
For websites that won't work, they are using a response header that won't allow their pages to be framed. You can work around this with some back-end program, where the server loads the web files then forwards them. 2
<!DOCTYPE html>
<html>
<head>
<title> Hello </title>
<style>
iframe {
display: block;
width: 1000px;
height: 500px;
margin-left: auto;
margin-right: auto;
}
iframe:focus {
outline: none;
}
button {
display: block;
margin: auto auto;
}
label {
display: block;
margin-left: auto;
margin-right: auto;
}
input {
display: block;
margin: auto auto;
}
</style>
</head>
<body>
<div id='main'>
<button id='wait' onclick='wait()'>Wait</button>
<label>Seconds</label>
<input type='number' id='seconds' placeholder='milliseconds'>
<button id='switching' onclick='webSwitch()'>Switch sites</button>
<iframe id='switchMe' src='https://codepen.io'></iframe>
</div>
<script>
//Array of webpages
var webList = ["https://www.bing.com", "https://www.walmart.com","https://www.codepen.io"];
//For tracking position in array
var count = 0;
//Function to be ran by event
function webSwitch() {
console.log('I have been called');
if (count >= webList.length) {
count = 0;
}
//Setting new URL
document.getElementById('switchMe').src = webList[count];
//Make sure to use next URL
count++;
}
function wait() {
console.log('Click!');
var numMS = document.getElementById('seconds').value;
sleep(numMS).then(() => {
webSwitch();
})
}
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
</script>
</body>
</html>

move shape to different directions

Task:
I created a shape with 4 buttons, and need it to move to 4 directions depending on the button clicked (pure JS).
This is what I created - check out the snippet.
Problem:
Left/Right directions work great, but Up/Down do not.
Any idea why? Looks like both directions are identical. :/
Thanks a lot for your help, much appreciated!
var shape = document.getElementById("shape"),
leftBtn = document.getElementById("leftBtn"),
rightBtn = document.getElementById("rightBtn"),
upBtn = document.getElementById("upBtn"),
downBtn = document.getElementById("downBtn");
leftBtn.onclick = function(){
moveLeft();
}
rightBtn.onclick = function(){
moveRight();
}
upBtn.onclick = function(){
moveUp();
}
downBtn.onclick = function(){
moveDown();
}
function moveLeft() {
var val = (parseInt(shape.style.left) || 0) - 50;
shape.style.left = val + "px";
}
function moveUp() {
var val = (parseInt(shape.style.top) || 0) - 50;
shape.style.left = val + "px";
}
function moveRight() {
var val = (parseInt(shape.style.left) || 0) + 50;
shape.style.left = val + "px";
}
function moveDown() {
var val = (parseInt(shape.style.top) || 0) + 50;
shape.style.left = val + "px";
}
body{
background-color: black;
}
#shape{
background-color: red;
width: 100px;
height: 100px;
border-radius: 50%;
position: relative;
}
<html>
<head>
<title>JavaScript and the Document Object Model</title>
<link rel="stylesheet" type="text/css" href="shape.css">
</head>
<body>
<div id="container">
<div id="shape">
</div>
<div id="buttons">
<button class="button" id="leftBtn" direction="left">left</button>
<button class="button" id="upBtn" direction="up">up</button>
<button class="button" id="downBtn" direction="down">down</button>
<button class="button" id="rightBtn" direction="right">right</button>
</div>
</div>
<script type="text/javascript" src="shape.js"></script>
</body>
</html>
As pointed by #Temani, in functions moveUp and moveDown, changing shape.style.left to shape.style.top will solve the problem.
var shape = document.getElementById("shape"),
leftBtn = document.getElementById("leftBtn"),
rightBtn = document.getElementById("rightBtn"),
upBtn = document.getElementById("upBtn"),
downBtn = document.getElementById("downBtn");
leftBtn.onclick = function(){
moveLeft();
}
rightBtn.onclick = function(){
moveRight();
}
upBtn.onclick = function(){
moveUp();
}
downBtn.onclick = function(){
moveDown();
}
function moveLeft() {
var val = (parseInt(shape.style.left) || 0) - 50;
shape.style.left = val + "px";
}
function moveUp() {
var val = (parseInt(shape.style.top) || 0) - 50;
shape.style.top = val + "px";
}
function moveRight() {
var val = (parseInt(shape.style.left) || 0) + 50;
shape.style.left = val + "px";
}
function moveDown() {
var val = (parseInt(shape.style.top) || 0) + 50;
shape.style.top = val + "px";
}
body{
background-color: black;
}
#shape{
background-color: red;
width: 100px;
height: 100px;
border-radius: 50%;
position: relative;
}
<html>
<head>
<title>JavaScript and the Document Object Model</title>
<link rel="stylesheet" type="text/css" href="shape.css">
</head>
<body>
<div id="container">
<div id="shape">
</div>
<div id="buttons">
<button class="button" id="leftBtn" direction="left">left</button>
<button class="button" id="upBtn" direction="up">up</button>
<button class="button" id="downBtn" direction="down">down</button>
<button class="button" id="rightBtn" direction="right">right</button>
</div>
</div>
<script type="text/javascript" src="shape.js"></script>
</body>
</html>

Javascript, JQuery Previous button

I need some help with this code. I want to create an event click button for previous. How can I do this using a little code? some thing similar to my Next button click event.
Here is my full code.
$(document).ready(function() {
var nextSlide = $("#slides img:first-child");
var nextCaption;
var nextSlideSource;
var counter = 0;
// the function for running the slide show
var runSlideShow = function() {
$("#caption").fadeOut(1000);
$("#slide").fadeOut(1000,
function () {
if (nextSlide.next().length === 0) {
nextSlide = $("#slides img:first-child");
}
else {
nextSlide = nextSlide.next();
}
nextSlideSource = nextSlide.attr("src");
nextCaption = nextSlide.attr("alt");
$("#slide").attr("src", nextSlideSource).fadeIn(1000);
$("#caption").text(nextCaption).fadeIn(1000);
}
);
};
// start the slide show
var timer = setInterval(runSlideShow, 3000);
$("#play").on("click", function() {
if($(this).val() === "Pause") {
clearInterval(timer);
$(this).val("Play");
$("#prev").prop("disabled", false);
$("#next").prop("disabled", false);
}
else if ($(this).val() === "Play") {
timer = setInterval(runSlideShow, 3000);
$(this).val("Pause");
$("#prev").prop("disabled", true);
$("#next").prop("disabled", true);
}
});
var imag = $("#slides img").index();
var imageSize = $("#slides img").length - 1;
$("#next").on("click", function (e) {
e.preventDefault();
if (imag === imageSize) {
$("#next").prop("disabled", true);
}
else {
++imag;
runSlideShow(1);
}
});
});
body {
font-family: Arial, Helvetica, sans-serif;
width: 380px;
height: 350px;
margin: 0 auto;
padding: 20px;
border: 3px solid blue;
}
h1, h2, ul, p {
margin: 0;
padding: 0;
}
h1 {
padding-bottom: .25em;
color: blue;
}
h2 {
font-size: 120%;
padding: .5em 0;
}
img {
height: 250px;
}
#slides img {
display: none;
}
#buttons {
margin-top: .5em;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Slide Show</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="slide_show.js"></script>
</head>
<body>
<section>
<h1>Fishing Slide Show</h1>
<h2 id="caption">Casting on the Upper Kings</h2>
<img id="slide" src="images/casting1.jpg" alt="">
<div id="slides">
<img src="images/casting1.jpg" alt="Casting on the Upper Kings">
<img src="images/casting2.jpg" alt="Casting on the Lower Kings">
<img src="images/catchrelease.jpg" alt="Catch and Release on the Big Horn">
<img src="images/fish.jpg" alt="Catching on the South Fork">
<img src="images/lures.jpg" alt="The Lures for Catching">
</div>
<div id="buttons">
<input type="button" id="prev" value="Previous" disabled>
<input type="button" id="play" value="Pause">
<input type="button" id="next" value="Next" disabled>
</div>
</section>
</body>
</html>
I thought of during it this way, but that is not working.
$("#prev").on("click", function () {
if (imag === imageSize) {
$("#prev").prop("disabled", true);
}
else {
++imag;
runSlideShow(-1);
}
});
Something similar to this Next button click event.
$("#next").on("click", function (e) {
e.preventDefault();
if (imag === imageSize) {
$("#next").prop("disabled", true);
}
else {
++imag;
runSlideShow(1);
}
});
Any help please.
test my idea =)
var mySlide = function(){
var index = 0;
var timer = false;
var self = this;
self.data = [];
self.start = function(){
timer = setInterval(self.next, 3000);
return self;
};
self.stop = function(){
clearInterval(timer);
timer = false;
return self;
};
self.pause = function(){
if(timer == false){
self.start();
} else {
self.stop();
}
};
self.next = function(){
if(self.data.length > 0){
self.stop().start(); // reset the timer
index++;
self.update();
}
};
self.prev = function(){
if(self.data.length > 0 && index > 0){
self.stop().start(); // reset the timer
index--;
self.update();
}
};
self.update = function(){
var item = self.data[index % self.data.length]; // calculating the value of INDEX
$('.print').fadeOut(1000,function(){
$(this).html(item).fadeIn(1000);
});
};
}
// RUN CODE!
var test = new mySlide();
test.data = [ // LOAD ITEM!
'food',
'bar',
$('<img/>').attr('src','https://www.google.it/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png')
];
test.start().update(); // START!
$('.prev').click(test.prev); // add event!
$('.pause').click(test.pause);
$('.next').click(test.next);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="print"></div>
<input type="button" value="prev" class="prev">
<input type="button" value="pause" class="pause">
<input type="button" value="next" class="next">

Uploading Multiple Files to Google Drive with Google App Script

I'm trying to upload multiple files at once with my app. It recognizes when there are 2 or more files being selected. However, it will only upload the 1st file that is selected to my drive. Also (although quite minor), I was wondering how I can change my textarea font to be Times New Roman to stay consistent with the rest of the font.
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('form')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFiles(form) {
try {
var foldertitle = form.zone + ' | Building: ' + form.building + ' | ' + form.propertyAddress + ' | ' + form.attachType;
var folder, folders = DriveApp.getFolderById("0B7UEz7SKB72HfmNmNnlSM2NDTVVUSlloa1hZeVI0VEJuZUhSTmc4UXYwZjV1eWM5YXJPaGs");
var createfolder = folders.createFolder(foldertitle);
folder = createfolder;
var blob = form.filename;
var file = folder.createFile(blob);
file.setDescription(" " + form.fileText);
return "File(s) uploaded successfully! Here is the link to your file(s): " + folder.getUrl();
} catch (error) {
Logger.log('err: ' + error.toString());
return error.toString();
}
}
function uploadArquivoParaDrive(base64Data, nomeArq, idPasta) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(nomeArq);
var file = DriveApp.getFolderById("0B7UEz7SKB72HfmNmNnlSM2NDTVVUSlloa1hZeVI0VEJuZUhSTmc4UXYwZjV1eWM5YXJPaGs").createFile(ss);
return file.getName();
}catch(e){
return 'Erro: ' + e.toString();
}
}
form.html
<body>
<div id="formcontainer">
<label for="myForm">Facilities Project Database Attachment Uploader:</label>
<br><br>
<form id="myForm">
<label for="myForm">Project Details:</label>
<div>
<input type="text" name="zone" placeholder="Zone:">
</div>
<div>
<input type="text" name="building" placeholder="Building(s):">
</div>
<div>
<input type="text" name="propertyAddress" placeholder="Property Address:">
</div>
<div>
<label for="fileText">Project Description:</label>
<TEXTAREA name="projectDescription"
placeholder="Describe your attachment(s) here:"
style ="width:400px; height:200px;"
></TEXTAREA>
</div>
<br>
<label for="attachType">Choose Attachment Type:</label>
<br>
<select name="attachType">
<option value="Pictures Only">Picture(s)</option>
<option value="Proposals Only">Proposal(s)</option>
<option value="Pictures & Proposals">All</option>
</select>
<br>
<label for="myFile">Upload Attachment(s):</label>
<br>
<input type="file" name="filename" id="myFile" multiple>
<input type="submit" value="Submit" onclick="iteratorFileUpload()">
</form>
</div>
<div id="output"></div>
<script>
function iteratorFileUpload() {
var allFiles = document.getElementById('myFile').files;
if (allFiles.length == 0) {
alert('No file selected!');
} else {
// Send each file one at a time
var i=0;
for (i=0; i < allFiles.total; i+=1) {
console.log('This iteration: ' + i);
sendFileToDrive(allFiles[i]);
};
};
};
function sendFileToDrive(file) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
google.script.run
.withSuccessHandler(fileUploaded)
.uploadArquivoParaDrive(content, file.name, currFolder);
}
reader.readAsDataURL(file);
};
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
// Upload de arquivo dentro das pastas Arquivos Auxiliares
function iterarArquivosUpload() {
var arquivos = document.getElementById('inputUpload').files;
if (arquivos.length == 0) {
alert('No file selected!');
} else {
//Show Progress Bar
numUploads.total = arquivos.length;
$('.progressUpload').progressbar({
value : false
});
$('.labelProgressUpload').html('Preparando arquivos para upload');
// Send each file at a time
for (var arqs = 0; arqs < numUploads.total; arqs++) {
console.log(arqs);
enviarArquivoParaDrive(arquivos[arqs]);
}
}
}
function enviarArquivoParaDrive(arquivo) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + arquivo.name);
google.script.run.withSuccessHandler(updateProgressbar).uploadArquivoParaDrive(content, arquivo.name, currFolder);
}
reader.readAsDataURL(arquivo);
}
function updateProgressbar( idUpdate ){
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total)*100);
$('.progressUpload').progressbar({value: porc });
$('.labelProgressUpload').html(numUploads.done +'/'+ numUploads.total);
if( numUploads.done == numUploads.total ){
uploadsFinished();
numUploads.done = 0;
};
}
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
body {
max-width: 400px;
padding: 20px;
margin: auto;
}
input {
display: inline-block;
width: 100%;
padding: 5px 0px 5px 5px;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌​ -moz-box-sizing: border-box;
box-sizing: border-box;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="submit"] {
width: auto !important;
display: block !important;
}
input[type="file"] {
padding: 5px 0px 15px 0px !important;
}
</style>
</body>
I know this question is old, but after finding it and related ones, I was never able to get the multiple file upload working. So after a lot of banging my head against walls, I wanted to post a full example (.html and .gs) in case anyone in the future is looking for one to get started. This is working when I deploy it right now and will hopefully work for other people out there. Note that I just hardcoded the folder in the drive to use in the code.gs file, but that can be easily changed.
form.html:
<body>
<div id="formcontainer">
<label for="myForm">Facilities Project Database Attachment Uploader:</label>
<br><br>
<form id="myForm">
<label for="myForm">Project Details:</label>
<div>
<input type="text" name="zone" placeholder="Zone:">
</div>
<div>
<input type="text" name="building" placeholder="Building(s):">
</div>
<div>
<input type="text" name="propertyAddress" placeholder="Property Address:">
</div>
<div>
<label for="fileText">Project Description:</label>
<TEXTAREA name="projectDescription"
placeholder="Describe your attachment(s) here:"
style ="width:400px; height:200px;"
></TEXTAREA>
</div>
<br>
<label for="attachType">Choose Attachment Type:</label>
<br>
<select name="attachType">
<option value="Pictures Only">Picture(s)</option>
<option value="Proposals Only">Proposal(s)</option>
<option value="Pictures & Proposals">All</option>
</select>
<br>
<label for="myFile">Upload Attachment(s):</label>
<br>
<input type="file" name="filename" id="myFile" multiple>
<input type="button" value="Submit" onclick="iteratorFileUpload()">
</form>
</div>
<div id="output"></div>
<div id="progressbar">
<div class="progress-label"></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
var allFiles = document.getElementById('myFile').files;
if (allFiles.length == 0) {
alert('No file selected!');
} else {
//Show Progress Bar
numUploads.total = allFiles.length;
$('#progressbar').progressbar({
value : false
});//.append("<div class='caption'>37%</div>");
$(".progress-label").html('Preparing files for upload');
// Send each file at a time
for (var i = 0; i < allFiles.length; i++) {
console.log(i);
sendFileToDrive(allFiles[i]);
}
}
}
function sendFileToDrive(file) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
var currFolder = 'Something';
google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);
}
reader.readAsDataURL(file);
}
function updateProgressbar( idUpdate ){
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total)*100);
$("#progressbar").progressbar({value: porc });
$(".progress-label").text(numUploads.done +'/'+ numUploads.total);
if( numUploads.done == numUploads.total ){
//uploadsFinished();
numUploads.done = 0;
};
}
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
body {
max-width: 400px;
padding: 20px;
margin: auto;
}
input {
display: inline-block;
width: 100%;
padding: 5px 0px 5px 5px;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌​ -moz-box-sizing: border-box;
box-sizing: border-box;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="submit"] {
width: auto !important;
display: block !important;
}
input[type="file"] {
padding: 5px 0px 15px 0px !important;
}
#progressbar{
width: 100%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;
}
.progress-label {
float: left;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
</body>
code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('form')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFileToDrive(base64Data, fileName) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(fileName);
var dropbox = "Something"; // Folder Name
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var file = folder.createFile(ss);
return file.getName();
}catch(e){
return 'Error: ' + e.toString();
}
}
Updated For May 2017
I updated and improved barragan's answer.
Advantages:
Allows users to create a subfolder name to contain all the files uploaded during this session
Ensures that these subfolders all exist within one specified folder within your Google Drive
The page/form is mobile-responsive
You can start with this example just to create the script and get to know the basics.
Then you can completely replace form.html with this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>
Send Files
</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
$(document).ready(function () {
function afterSubfolderCreated(subfolderId) {
console.log(subfolderId);
console.log(allFiles);
numUploads.total = allFiles.length;
$('#progressbar').progressbar({
value: false
});
$(".progress-label").html('Preparing files for upload');
for (var i = 0; i < allFiles.length; i++) {
console.log(i);
sendFileToDrive(allFiles[i], subfolderId);
}
}
function sendFileToDrive(file, subfolderId) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, subfolderId);
}
reader.readAsDataURL(file);
}
function updateProgressbar(idUpdate) {
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total) * 100);
$("#progressbar").progressbar({value: porc});
$(".progress-label").text(numUploads.done + '/' + numUploads.total);
if (numUploads.done == numUploads.total) {
numUploads.done = 0;
$(".progress-label").text($(".progress-label").text() + ': FINISHED!');
$("#progressbar").after('(Optional) Refresh this page if you remembered other screenshots you want to add.');//<a href="javascript:window.top.location.href=window.top.location.href"> does not work
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
var allFiles;
var frm = $('#myForm');
frm.submit(function () {
allFiles = document.getElementById('myFile').files;
if (!frm.checkValidity || frm.checkValidity()) {
if (allFiles.length == 0) {
alert('Error: Please choose at least 1 file to upload.');
return false;
} else {
frm.hide();
var subfolderName = document.getElementById('myName').value;
$.ajax({
url: '',//URL of webhook endpoint for sending a Slack notification
data: {
title: subfolderName + ' is uploading screenshots',
message: ''
}
});
google.script.run.withSuccessHandler(afterSubfolderCreated).createSubfolder(subfolderName);
return false;
}
} else {
alert('Invalid form');
return false;
}
});
});//end docReady
</script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<style>
body {
padding: 20px;
margin: auto;
font-size: 20px;
}
label{
font-weight: bold;
}
input{
font-size: 20px;
padding: 5px;
display: inline-block;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌-moz-box-sizing: border-box;
box-sizing: border-box;
}
.hint{
font-size: 90%;
color: #666;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="file"] {
padding: 5px 0px 15px 0px;
}
#progressbar{
width: 100%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;
}
.progress-label {
float: left;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
li{
padding: 10px;
}
#media only screen and (max-width : 520px) {
#logo {
max-width: 100%;
}
}
</style>
</head>
<body>
<p>
<img src="" id="logo">
</p>
<p>This webpage allows you to send me screenshots of your dating profiles.</p>
<ol>
<li>
In each of your dating apps, take a screenshot (how?) of every part of every page of your profile.
</li>
<li>
Do the same for each of your photos (at full resolution).
</li>
<li>
In the form below, type your first name and last initial (without any spaces or special characters), such as SallyT.
</li>
<li>
Then click the first button and select all of your screenshot images (all at once).
</li>
<li>
Finally, press the last button to send them all to me!
</li>
</ol>
<form id="myForm">
<div>
<label for="myName">Your first name and last initial:</label>
</div>
<div>
<input type="text" name="myName" id="myName" placeholder="SallyT" required pattern="[a-zA-Z]+" value="">
</div>
<div>
<span class="hint">(No spaces or special characters allowed because this will determine your folder name)</span>
</div>
<div style="margin-top: 20px;">
<label for="myFile">Screenshot image files:</label>
<input type="file" name="filename" id="myFile" multiple>
</div>
<div style="margin-top: 20px;">
<input type="submit" value="Send File(s) ➔" >
</div>
</form>
<div id="output"></div>
<div id="progressbar">
<div class="progress-label"></div>
</div>
</body>
</html>
And completely replace server.gs with this:
function doGet() {
var output = HtmlService.createHtmlOutputFromFile('form');
output.addMetaTag('viewport', 'width=device-width, initial-scale=1');// See http://stackoverflow.com/a/42681526/470749
return output.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFileToDrive(base64Data, fileName, subfolderId) {
Logger.log(subfolderId);
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(fileName);
var subfolder = DriveApp.getFolderById(subfolderId);
var file = subfolder.createFile(ss);
Logger.log(file);
return file.getName() + ' at ' + file.getUrl();
} catch(e){
return 'createFile Error: ' + e.toString();
}
}
function createSubfolder(subfolderName){
var dropbox = subfolderName + Utilities.formatDate(new Date(), "US/Eastern", "_yyyy-MM-dd");
Logger.log(dropbox);
var parentFolderId = "{ID such as 0B9iQ20nrMNYAaHZxRjd}";
var parentFolder = DriveApp.getFolderById(parentFolderId);
var folder;
try {
folder = parentFolder.getFoldersByName(dropbox).next();
}
catch(e) {
folder = parentFolder.createFolder(dropbox);
}
Logger.log(folder);
return folder.getId();
}
Joining the pile of older answers, but this really helped me when I implemented my own file multi upload for getting files into Google Drive using the DriveApp V3 api.
I wrote and posted my own solution here: https://github.com/CharlesPlucker/drive-multi-upload/
Improvements:
- Handles multiple files sequentially
- Handles large > 50MB files
- Validation
I wrapped my google api calls into promises since I was running into timing issues when creating a folder and immediately trying to fetch it by name reference. Each one of my promises will only resolve when its file is fully uploaded. To get that working I had to use a Promise Factory. I'll be glad to explain this code if the need arises!
You have to send a file at a time trough the script.run, here's my implementation with FileReaders/ReadAsURL, which makes the file a Base64 string, which can be easily passed around:
Notes:
Dunno if it's necessary but I'm using IFRAME sandbox
I left the progressBar in the code, you can remove it
Everything must be OUTSIDE a form
It accepts any file type
HTML:
// Upload de arquivo dentro das pastas Arquivos Auxiliares
function iterarArquivosUpload() {
var arquivos = document.getElementById('inputUpload').files;
if (arquivos.length == 0) {
alert('No file selected!');
} else {
//Show Progress Bar
numUploads.total = arquivos.length;
$('.progressUpload').progressbar({
value : false
});
$('.labelProgressUpload').html('Preparando arquivos para upload');
// Send each file at a time
for (var arqs = 0; arqs < numUploads.total; arqs++) {
console.log(arqs);
enviarArquivoParaDrive(arquivos[arqs]);
}
}
}
function enviarArquivoParaDrive(arquivo) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + arquivo.name);
google.script.run.withSuccessHandler(updateProgressbar).uploadArquivoParaDrive(content, arquivo.name, currFolder);
}
reader.readAsDataURL(arquivo);
}
function updateProgressbar( idUpdate ){
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total)*100);
$('.progressUpload').progressbar({value: porc });
$('.labelProgressUpload').html(numUploads.done +'/'+ numUploads.total);
if( numUploads.done == numUploads.total ){
uploadsFinished();
numUploads.done = 0;
};
}
Code.GS
function uploadArquivoParaDrive(base64Data, nomeArq, idPasta) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(nomeArq);
var file = DriveApp.getFolderById(idPasta).createFile(ss);
return file.getName();
}catch(e){
return 'Erro: ' + e.toString();
}
}
as #barragan's answer here is the best answer i found after hours and hours of searching for a question many people were asking, i've done a bit of development to improve the design a bit for others as a thanks. still a few bugs and chrome seems to run out of memory and give up with any file over 100MB
here's a live version
server.gs
'function doGet() {
return HtmlService.createHtmlOutputFromFile('form')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFileToDrive(base64Data, fileName) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(fileName);
var dropbox = "Something"; // Folder Name
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var file = folder.createFile(ss);
return file.getName();
}catch(e){
return 'Error: ' + e.toString();
}
}
'
form.html
<head>
<base target="_blank">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Focallocal Uploader</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
<div align="center">
<p><img src="http://news.focallocal.org/wp-content/uploads/2015/03/FOCALLOCAL-Website-Text-Header.png" width="80%"></p>
</div>
</head>
<body>
<div id="formcontainer" width="50%">
<label for="myForm">Focallocal Community G.Drive Uploader</label>
<br>
<br>
<form id="myForm" width="50%">
<label for="myForm">Details</label>
<div>
<input type="text" name="Name" placeholder="your name">
</div>
<div>
<input type="text" name="gathering" placeholder="which fabulous Positive Action you're sending us">
</div>
<div>
<input type="text" name="location" placeholder="the town/village/city and country month brightend by positivity">
</div>
<div>
<input type="text" name="date" placeholder="date of the beautiful action">
</div>
<div width="100%" height="200px">
<label for="fileText">would you like to leave a short quote?</label>
<TEXTAREA name="Quote"
placeholder="many people would love to share in your experience. if you have more than a sentence or two to write, why not writing an article the Community News section of our website?"
></TEXTAREA>
</div>
<br>
<br>
<label for="myFile">Upload Your Files:</label>
<br>
<input type="file" name="filename" id="myFile" multiple>
<input type="button" value="Submit" onclick="iteratorFileUpload();">
</form>
</div>
<div id="output"></div>
<div id="progressbar">
<div class="progress-label"></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
var allFiles = document.getElementById('myFile').files;
if (allFiles.length == 0) {
alert('No file selected!');
} else {
//Show Progress Bar
numUploads.total = allFiles.length;
$('#progressbar').progressbar({
value : false
});//.append("<div class='caption'>37%</div>");
$(".progress-label").html('Preparing files for upload');
// Send each file at a time
for (var i = 0; i < allFiles.length; i++) {
console.log(i);
sendFileToDrive(allFiles[i]);
}
}
}
function sendFileToDrive(file) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
var currFolder = 'Something';
google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);
}
reader.readAsDataURL(file);
}
function updateProgressbar( idUpdate ){
console.log('Received: ' + idUpdate);
numUploads.done++;
var porc = Math.ceil((numUploads.done / numUploads.total)*100);
$("#progressbar").progressbar({value: porc });
$(".progress-label").text(numUploads.done +'/'+ numUploads.total);
if( numUploads.done == numUploads.total ){
//uploadsFinished();
numUploads.done = 0;
};
}
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
body {
max-width: 60%;
padding: 20px;
margin: auto;
}
input {
display: inline-block;
width: 50%;
padding: 5px 0px 5px 5px;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌​ -moz-box-sizing: border-box;
box-sizing: border-box;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="submit"] {
width: auto !important;
display: block !important;
}
input[type="file"] {
padding: 5px 0px 15px 0px !important;
}
#progressbar{
width: 40%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;
}
.progress-label {
float: left;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
</body>
i wasn't able to get the text fields to send an email with the details out, and ran out of time before working out how to hook them up to a Google Spreadsheet, so for the moment they don't record the information added
as an added bonus, it looked fabulous with is in the form.html
<div class="fixed-action-btn horizontal" style="bottom: 45px; right: 24px;">
<a class="btn-floating btn-large red">
<i class="large material-icons">menu</i>
</a>
<ul>
<li><a class="btn-floating red" href="https://focallocal-a-positive-action-movement.myshopify.com/" target="_blank" title="Pimp your Cool at the Positive Action Shop"><i class="material-icons">monetization_on</i></a></li>
<li><a class="btn-floating blue" href="https://www.youtube.com/user/Focallocal" target="_blank" title="Follow the Positive Action Youtube Channel"><i class="material-icons">video_library</i></a></li>
<li><a class="btn-floating green" href="http://focallocal.org/" target="_blank" title="Read our About Us Page"><i class="material-icons">help</i></a></li>
</ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
<script src="https://gumroad.com/js/gumroad.js"></script>
i took it out again as some of the scripts being called in were causing issues. if anyone can fix them it they add a lot to the appearance and functionality of the form
*edit: i've been playing around with it and only around half of the files sent seem to arrive, so there are still some issues with both of the codes here atm

Categories