How to make an input file todataurl for use? - javascript

I would like to grab a file from the input tag and convert it to a URL then display that URL in the paragraph tag.
Is this possible with only Javacript/HTML?
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.12.0.min.js"></script>
</head>
<body>
<form action="demo_form.asp">
<input type="file" id="wow" name="pic" accept="image/*">
</form>
<script>
$("document").ready(function(){
$("#wow").change(function() {
document.getElementById("penut").innerHTML = document.getElementById("wow").files.toDataUrl();
});
});
</script>
<p id="penut"></p>
</body>
</html>

Six days later but I found some code that does it.
<p>Select a File to Load:</p>
<input id="inputFileToLoad" type="file" onchange="loadImageFileAsURL();" />
<p>File Contents as DataURL:</p>
<textarea id="textAreaFileContents" style="width:640;height:240" ></textarea>
<script type="text/javascript">
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textAreaFileContents = document.getElementById
(
"textAreaFileContents"
);
textAreaFileContents.innerHTML = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
</body>
</html>

Related

Upload image into Google Drive via Web App and save correspondent link on spreadsheet

This is my first approach with js and html coding, please be as much simple as possible!
I want to improve the form developed in my web App making possible to upload image. My goal is to:
Add input type file on my web App
Send the file to server side
Save the file in the G Drive, take the link and save it in Google Sheet
To do this I have already added in my html a file input area, but I'm not sure about how I may manage it in script section.
All the information added in the form are send to server in an object called measureInfo and I want to maintain this routine. When I try to add
measureInfo.media = document.getElementById('fileUpload').files
it doesn't run and console return `Failed due to illegal value in property: media.
Here I report some string of code that may help to answer. If you have some suggests about how manage file in server side with DriveApp please share!
<script>
measureInfo.media= document.getElementById('fileUpload').files
google.script.run.sendToDatabase(measureInfo);
</script>
<form action="#">
<!-- Upload File -->
<div class="file-field input-field">
<div class="btn-large blue darken-3">
<span>Media</span>
<input type="file" id= 'fileUpload' name ='fileUpload'>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder = 'Upload Media'>
</div>
</div>
</form>
You could use FileReader.onload event to build an object that can be passed server-side:
const file = document.getElementById('fileUpload').files[0];
const fr = new FileReader();
fr.onload = (e) => {
const data = e.target.result.split(",");
measureInfo.media = {fileName: file.name, mimeType: file.type, data: data[1]};
google.script.run.sendToDatabase(measureInfo);
}
fr.readAsDataURL(file);
Reference:
FileReader.onload
Uploading Multiple Files From Local To Google Drive using Google Apps Script
Here's some code I use for saving receipts:
HTML with JS:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
<style>
input,textarea{margin:5px 5px 5px 0;}
</style>
</head>
<body>
<h3 id="main-heading">Receipt Information</h3>
<div id="formDiv">
<form id="myForm">
<br /><input type="date" name="date" id="dt"/>
<br /><input type="number" name="amount" placeholder="Amount" id="amt" />
<br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
<br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
<br/>Receipt Image
<br /><input type="file" name="receipt" id="img" />
<br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
</form>
</div>
<div id="status" style="display: none">
<!-- div will be filled with innerHTML after form submission. -->
Uploading. Please wait...
</div>
</body>
</html>
GS:
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Receipt Information').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd");
return {date:datestring};
}
<script>
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.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
<script>
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Receipt Information').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd");
return {date:datestring};
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<base target="_top">
<?!= include('JavaScript'); ?>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<head>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
</head
<body>
<div class="form-row">
<div class="form-group col-md-12">
<h5 style="text-align:center;">Upload Photo</h5>
<div class="form-row">
<div class="form-group col-md-4" style="word-wrap: break-word">
<p3 style="text-align:left; color:red">
Notice! Please doff eyewear & mask and avoid sunlight exposure when taking selfie!</p>
</div>
<div class="form-group col-md-6"><img id="output" width="200" height="200" src="https://www.citypng.com/public/uploads/small/116395943260tji5ordfujy44njydzhlidv8reqpmtun7ggx1oszpz1dcistzxnmag7do6vxkjxphlsgueuurkg9pkpbwgorvv9lratpxm38rp5.png" alt="photo" style="border:gray; border-width:2px; border-style:solid;"/></div>
<div class="form-group col-md-12">
<center>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input class="file-path validate" type="file" id="fileUpload" name="fileUpload" value='fileUpload' accept="image/*" onchange="loadFile(event)">
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
</div>
</body>
</html>
[1]: https://i.stack.imgur.com/98vPf.png

How selec .txt file from pc an paste the content to text area on html5

Hi everyone i'm trying to use Jquery and Modernizr to select 1 .txt file from my pc
I have the next code on my project:
<!DOCTYPE html>
<html>
<head>
<title>Read file on HTML5</title>
<meta charset="UTF-8">
<script src="jquery-3.5.1.min.js" type="text/javascript"></script>
<script src="modernizr.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (Modernizr.draganddrop && window.FileList) {
} else {
alert("Your browser doesn't support API or Drag&Drop");
}
;
$('#file').change(filedriver);
function filedriver(event) {
var file = event.target.files[0];
if(file.type !== "text/plain"){
alert("File .txt must be select");
return;
}
var reader = new FileReader();
reader.onload = function(event){
var textResult = event.target.result;
$('content').append(textResult);
};
reader.readAsText(file);
}
});
</script>
</head>
<body>
<h1>Read file on HTML5</h1>
<form>
<label>Select file </label>
<input type="file" name="file" id="file" />
<p>Content on file</p>
<textarea cols="100" rows="15" id="content"></textarea>
</form>
</body>
</html>
When i execute the proyect on my browser the validation for the file works, but the reader doesn't return the content on the file.
¿where it's my error?
https://www.dropbox.com/s/sxrvou2spfdjgte/LecturaArchivoTexto.rar?dl=0
enter image description here

threshold() Please input the valid canvas or img id error

I have a problem with cv.threshold() function in opencv.js library.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="opencv.js" type="text/javascript"></script>
</head>
<body>
<h2>Hello OpenCV.js</h2>
<p id="status">OpenCV.js is loading...</p>
<div>
<div class="inputoutput">
<img id="imageSrc" alt="No Image" />
<div class="caption">imageSrc <input type="file" id="fileInput" name="file" /></div>
</div>
<div class="inputoutput">
<canvas id="canvasInput" ></canvas>
</div>
<div class="inputoutput2">
<canvas id="canvasOutput" ></canvas>
</div>
</div>
<script type="text/javascript">
let image1=cv.imread('bookpage.jpg');
let threshold;
cv.threshold(image1,threshold,12,250,THRESH_BINARY);
cv.imshow('canvasInput',image);
cv.imshow('canvasOutput',threshold);
</script>
</body>
</html>
Error:
Uncaught Error: Please input the valid canvas or img id.
at Object.Module.imread (/C:/Users/q/Desktop/web/opencv.js/4-)Thresholding/opencv.js:56:20361)
How can I fix that error?
You need to pass in a canvas or image ID as stated in the error message. You're passing it a file name. Sample code from the docs
OpenCV docs
<script type="text/javascript">
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
imgElement.onload = function() {
let mat = cv.imread(imgElement);
cv.imshow('canvasOutput', mat);
mat.delete();
};
function onOpenCvReady() {
document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
</script>

FileTransfer() undefined when uploading a file

I am trying to upload file in my mobile app, i have installed file-transefer plugin, as well as file plugin but FileTransfer() givs undefined value
my javascript and HTMLcode is as follows
function uploadPhoto() {
var imageURI = document.getElementById('imgUpld').getAttribute("src");
if (!imageURI) {
alert('Please select an image first.');
return;
}
//set upload options
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://Some-serverpath/documents/"), win, fail, options);
}
HTML Code:
Submit form
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
<body>
<form enctype="multipart/form-data">
<input id="fileUpload" type="file" style=" width:100%;"
class="filestyle" data-input="false"
data-buttontext="Upload Doc.">
<div id="image-holder" class="virtualPlaceholder"> </div>
<input type="button" id="btnSubmit" value="Submit">
</form>
</body>
<script src="../scripts/jquery-1.11.3.min.js"></script>
<script src="../scripts/bootstrap.js"></script>
<script src="../scripts/bootstrap.min.js"></script>
<script src="../scripts/Fileupload.js"></script>
<script src="../scripts/FileTransfer.js"></script>
<script src="../scripts/FileTransferError.js"></script>
<script src="../scripts/FileUploadOptions.js"></script>
<script src="../scripts/FileUploadResult.js"></script>
/body>
Is there any solution? Thanks in Advance

javascript: how to select and parse a file

Javascript novice, looking to write a program that takes an input file, filenames.txt, tests each line to see if it contains a file path that is > 256 characters, and then outputs the results both as on-screen text and as a serializable format, i.e. .csv
here's the code that I have so far, I'm asking how to access the file selected and parse it for paths longer than 256 characters
<html>
<head>
<title>256 character finder</title>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
Pick a file:
<br>
<input id="lefile" type="file" style="display:none">
<div class="input-append">
<input id="fileSelect" class="input-large" type="text">
<a class="btn" onclick="$('input[id=lefile]').click();">Browse</a>
</div>
<div>
<input type="text" value="whatever" class="field left" readonly>
</div>
</body>
<script type="text/javascript">
$(document).ready(function() {
$('input[id=lefile]').change(function() {
$('#fileSelect').val($(this).val());
});
}
</script>
</html>
http://jsfiddle.net/Fcg2X/
Try this:
$(document).ready(function() {
$('[type=file]').change(function() {
if (!("files" in this)) {
alert("File reading not supported in this browser");
}
var file = this.files && this.files[0];
if (!file) {
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var text = e.target.result;
//do something with text
document.body.innerHTML = text;
};
fileReader.readAsText(this.files[0]);
});
});
Btw non-supporting browsers include IE9 so be aware. Has been working for years in Firefox and Chrome though.

Categories

Resources