Uncaught ReferenceError: LoadFile is not defined Error - javascript

When I run this code:
<!DOCTYPE html>
<html>
<head>
<title>Upload Button</title>
</head>
<body>
<input type="file" accept="image/*" style="display:none" onchange="LoadFile(event)" id="file" name="image"/>
<label for="file" style="cursor:pointer">Upload image</label>
<br>
<img id="output" style="width:200px; height:200px;"/>
<script>
var loadFile = function(event) {
var image = document.getElementById("output");
image.src = URL.createObjectURL(event.target.files[0]);
};
</script>
</body>
</html>
The browser throws this error:
Uncaught ReferenceError: LoadFile is not defined at HTMLInputElement.onchange (tp1.html:7)
It says that function LoadFile() isn't defined and I found this strange because the function is defined.

JavaScript is case-sensitive. You should call loadFile() instead of LoadFile() in onchange.
Here's your code:
<html>
<head>
<title>Upload Button</title>
</head>
<body>
<input type="file" accept="image/*" style="display:none;" onchange="loadFile(event)" id="file" name="image"/>
<label for="file" style="cursor:pointer">Upload image</label>
<br>
<img id="output" style="width:200px; height:200px;"/>
<script>
var loadFile = function(event) {
var image = document.getElementById("output");
image.src = URL.createObjectURL(event.target.files[0]);
};
</script>
</body>
</html>
Or change loadFile() to LaodFile():
<html>
<head>
<title>Upload Button</title>
</head>
<body>
<input type="file" accept="image/*" style="display:none;" onchange="LoadFile(event)" id="file" name="image"/>
<label for="file" style="cursor:pointer">Upload image</label>
<br>
<img id="output" style="width:200px; height:200px;"/>
<script>
var LoadFile = function(event) {
var image = document.getElementById("output");
image.src = URL.createObjectURL(event.target.files[0]);
};
</script>
</body>
</html>

The function you declared is "loadFile", but you use "LoadFile" in onchange.

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

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>

How to make an input file todataurl for use?

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>

How can I upload file in JavaScript and PHP without using FormData

I try to make upload page without refresh, when I select the file and press the button it does not come back with the file information if I use value, it gives me c:/fakepath/filename or undefined. I just want to upload file without using FormData.
Here is the code
<!doctype html>
<html lang="en">
<head><script src="http://localhost/jquery-1.10.2.js"></script></head>
<body>
<form enctype="multipart/form-data">
<input type="file" name="up[]" multiple>
<input type="file" name="up[]">
<input type="file" name="upload">
</form>
<script>
$( "form" ).submit(function( event ) {
event.preventDefault();
});
function omg(){
var elements= $( "form>*" );
$formdata=new FormData();
for(i=0;i<elements.length;i++){
var element=elements[i];
var elementtype=element.type;
var elementname=element.name;
if(elementtype == "file"){
if(element.value !== ""){
var files=element.files;
alert(files.name);
$("div").append(element.value + "<BR>");
}
}
}
}
</script>
</body>
</html>
Like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>File upload</title>
</head>
<body>
<form action="fileupload.php" enctype="multipart/form-data" target="myFrame">
<input type="file" name="up[]" multiple>
<input type="file" name="up[]">
<input type="file" name="upload">
<input type="submit" value="send">
</form><iframe style="display:hidden" name="myFrame"></iframe>
</body>
</html>

consolidate file choose and upload in one line in angularJs only

Currently, I choose the file and upload using 2 different buttons as follows:
<input type="file" file-model="myFile" />
<button ng-click="uploadFile()">upload me</button>
Is it possible to choose the file and upload in 1 single button?
I tried the following but did not work.
<input type="file" file-model="myFile" onchange="uploadFile()" />
You can use ng-file-select like this:
<input type="file" ng-model="fname" ng-file-select="uploadFile($files)">
Inside your controller, you'll get object:
$scope.uploadFile = function($files) {
var file = $files[0];
console.log(file);
}
More details:
http://blog.gitbd.org/file-upload-by-angular-and-php/
try this
<input type="file" file-model="myFile" onChange="uploadFile()" />
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
function uploadFile(){
alert("function accessed");
}
</script>
</head>
<body>
<input type="file" file-model="myFile" onChange="uploadFile()" />
</body>
</html>

Categories

Resources