Problem with Upload file to Google Drive using google script - javascript

I used these AttachFileFromJS() before and it work properly but that is in webapp deployment
,but this code has error when run inside modal on google sheet
(I'm not quite sure that make any difference?)
Code.gs
function UploadToDrive(){
var ui = SpreadsheetApp.getUi();
var html = HtmlService.createHtmlOutputFromFile('Upload').setWidth(400).setHeight(300);
ui.showModelessDialog(html," ");
}
function AttachFileFromJS(folderId,fileObj){
var folder = DriveApp.getFolderById(folderId);
if(fileObj.fileName != ''){
var data = Utilities.base64Decode(fileObj.fileData);
var blob = Utilities.newBlob(data, fileObj.mimeType, fileObj.fileName);
var createFile = folder.createFile(blob);
var picId = createFile.getId() ;
return picId ;
}
}
function Uploader(fileObj){
var folderId = '1VaRzewFKEUWL3DJ_uf7z6lIocFqu0P6j';
AttachFileFromJS(folderId,fileObj)
}
Upload.html (show only some part)
<div id="attach" name="attach">
<input type="file" name="file" id="fileInput" onchange="LoadFile(event)" />
<input type="hidden" id="fileData" name="fileData" />
<input type="hidden" id="mimeType" name="mimeType" />
<input type="hidden" id="fileName" name="fileName" />
</div><br>
<div class="form-group">
<button type="button" class="form-control btn btn-primary rounded submit px-3" onclick="UploadFile()" >Upload File</button>
</div>
Javascript
function LoadFile(event)
{
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result);
var fileData = e.target.result.substr(e.target.result.indexOf(",")+1);
var mimeTypeStart = e.target.result.indexOf("data:") + 5;
var mimeTypeEnd = e.target.result.indexOf(";");
var mimeType = e.target.result.substr(mimeTypeStart, mimeTypeEnd - mimeTypeStart);
var fileName = file.name;
document.getElementById("fileData").value = fileData;
document.getElementById("mimeType").value = mimeType;
document.getElementById("fileName").value = fileName;
};
reader.readAsDataURL(file);
}
function UploadFile(){
var File1 = {};
File1.fileData = document.getElementById("fileData").value ;
File1.mimeType = document.getElementById("mimeType").value ;
File1.fileName = document.getElementById("fileName").value ;
google.script.run.Uploader(File1) ;
}

Related

How to get XML file content in React? [duplicate]

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

Not removing value from multifile

I'm running the following to upload and remove any file if clicked:
$(document).on('click','.close',function(){
$(this).parents('span').remove();
})
document.getElementById("usp-files").onchange = function () {
document.getElementById("uploadFile").value = this.value;
};
document.getElementById('usp-files').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var files = $('#usp-files')[0].files;
for (var i = 0; i < files.length; i++) {
$("#upload_prev").append('<span>'+files[i].name+'<p class="close">X</p></span>');
}
document.getElementById('filename').value = filename;
}
HTML
<input type="hidden" id="uploadFile" placeholder="Add files from My Computer" class="steptextboxq3"/>
<div class="fileUpload btn btn-primary">
<span>Browse</span>
<input name="usp-files[]" id="usp-files" type="file" maxlength="999999" data-required="false" placeholder="Upload your images here" class="upload sp-input usp-input-files my_images select-file multiple" multiple="multiple" name="browsefile">
</div>
<input id="filename" type="hidden" />
<div id="upload_prev"></div>
Visually, we can see that it is removing it, but when I then send it to the server, it is saving all the files I have uploaded even tho I have removed them in front end.
jsFiddle here

File not found exception when trying to get drag and drop image in java

My code as follows
<script>
var formData = new FormData();
var doc = document.documentElement;
var files;
doc.ondragover = function () {
this.className = 'hover';
document.getElementById("image-div").style.border = "dotted";
return false;
};
doc.ondragend = function () {
document.getElementById("image-div").style.border = "solid";
this.className = '';
return false;
};
doc.ondrop = function (event) {
document.getElementById("image-div").style.border = "solid";
event.preventDefault && event.preventDefault();
this.className = '';
files = event.dataTransfer.files[0];
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
var fileReader = new FileReader();
fileReader.onload = function (event)
{
document.getElementById("previewImg").src = event.target.result;
}
fileReader.readAsDataURL(files);
return false;
};
jQuery.ajax({
url: 'URL',
data: formData,
processData: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
</script>
<body>
<form class="box" method="post" action="URL" id='SubmitForm' enctype="multipart/form-data">
<div class="image" style="border-style: solid;border-color: yellow;height: 300px;width: 300px;text-align: center;margin: 10px" id="image-div">
<p><label for="file"><strong>Choose a file</strong></label><span class="hide" id="drag"> or drag it here</span>.</p>
</div>
<div id="previewImage" style="display:none;border:1px solid black">
<img src="#" id="previewImg" style="width:250px;height:auto">
</div>
<div>
<input type='file' class="inputfile" name='file' id="file" accept='image/*' />
<input type='submit' value='Upload' name='Upload image' />
</div>
</form>
</body>
Exception at this line
InputStream fileContent = formFile.getInputStream();
Exception:
java.lang.RuntimeException: java.io.FileNotFoundException:
C:\Windows\TEMP\upload_723aa03a_1e6b_457a_b020_b33fc078881b_00000001.tmp
(The system cannot find the file specified)

How to upload multiple files through one upload button

When I am executing it not all of my files are uploaded but just one of them.
JavaScript
function upload() {
document.getElementById("uploading").innerHTML="uploading....";
var myfile=document.getElementById("fileinput").files[0];
//alert(myfile.size);
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
parseContents(contents);
//document.getElementById("cont").innerHTML=fileContent;
document.getElementById("uploading").innerHTML="<h3>File uploaded: "+myfile.name;
}
r.readAsText(myfile);
}
HTML
<body onload="initialize()">
<div id="container1"><h>MY TRANSIT PLANNER</h></div>
<h3 style="text-decoration:underline;">choose a file for input:</h3>
<input type="file" id="fileinput" multiple="multiple"onchange="upload()"/>
<br>
<div style="color: black" id="uploading"></div>
<script src="https://maps.googleapis.com/maps/api/js?"async defer></script>
<input type="button" id="btn-sgtd" type="text" value="SAVE GTD" onclick="writetofile()"/>
<h3 style="text-decoration:underline;">Choose files to Segment: </h3>
<form action="files.php" method="POST" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple="multiple"><br>
<br>
<input type="submit" value="SEGMENT" class="button"><br>
</form>
<div id="map"></div>
</body>
you should do loop
function upload() {
for (var i = 0; i < document.getElementById("fileinput").files.length; i++)
{
document.getElementById("uploading").innerHTML="uploading....";
var myfile=document.getElementById("fileinput").files[i];
//alert(myfile.size);
var r = new FileReader();
r.onload = function(e)
{
var contents = e.target.result;
parseContents(contents);
//document.getElementById("cont").innerHTML=fileContent;
document.getElementById("uploading").innerHTML="<h3>File uploaded: "+myfile.name;
}
r.readAsText(myfile);
}
}
try this will help you
function upload() {
document.getElementById("uploading").innerHTML="uploading....";
var myfile=document.getElementById("fileinput").files[0];
//alert(myfile.size);
var r = new FileReader();
r.onload = function(e) {
if(!e.target.files) return;
var files = e.target.files;
for(var i=0; i < files.length; i++) {
var f = files[i];
document.getElementById("uploading").innerHTML="<h3>File uploaded: "+f;
}
}

JS read image and show

function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; i<2 ; i++){
f = files[i]
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile){
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,'" title="',escape(theFile.name), '"/>'].join('');
document.getElementById('pic'+i).insertBefore(span, null);
};
})(f,i);
reader.readAsDataURL(f);
}
}
I have this script from HERE, EXAMPLE 3 and i am trying to put every file in different place.
<tr><td colspan="2"><input type="file" id="inputFilesID" multiple ></td></tr>
<tr><td>Front</td><td><output id="pic0" /></td></tr>
<tr><td>Back</td><td><output id="pic1" /></td></tr>
For example, if that is mine html, why if i put 2 images my script trying to put everything at:
<tr><td>Bottom</td><td><output id="pic2" /></td></tr>
//Logic in Scripts.js
var canvas = document.getElementById('our-canvas'),
context = canvas.getContext('2d');
uploadedFile = document.getElementById('uploaded-file');
window.addEventListener('DOMContentLoaded',initImageLoader) ;
function initImageLoader(){
uploadedFile.addEventListener('change',handleManualUploadedFiles);
function handleManualUploadedFiles(ev){
var file = ev.target.files[0];
handleFile(file);
}
}
function handleFile(file){
var ImageType = /image.*/;
if(file.type.match(ImageType)){
var reader = new FileReader();
reader.onloadend = function(event){
var tempImageStore = new Image();
tempImageStore.onload = function(ev){
canvas.height = ev.target.height;
canvas.width = ev.target.width;
context.drawImage(ev.target,0,0);
}
tempImageStore.src = event.target.result;
}
reader.readAsDataURL(file);
}
}
//Showing in HTML
<b>our image canvas </b>
<input type="file" id="uploaded-file" />
<canvas id= "our-canvas" class="image-container"> </canvas>
<script src="scripts.js" > </script>
use npm jimp
============================
Jimp.read('./path/to/image.jpg')
.then(image => {
console.log(image.bitmap)//having the image buffer data,width,height ...etc
// Do stuff with the image.
})
.catch(err => {
// Handle an exception.
});

Categories

Resources