I want zip a pdf or some other format like excel, ppt etc using zip.js.
How to zip this format in zip.js? I have written but I failed in generating the zip file. My requirement is to download the zip file when I click the download button. How to do this? I am completely stuck in generating the zip file.
My code is as below
<body>
<a id ='file' href="http://www.brainlens.org/content/newsletters/Spring%202013.pdf" type="application/pdf" name="Sample.pdf">Sample.pdf</a>
<input id="button" type="button" value="Create Zip"></input>
</body>
<script>
var FILENAME = document.getElementById('file').name;//"sample.pdf"
var URL = document.getElementById('file').href;//"sample.pdf"
var zipFs = new zip.fs.FS();
function zipPDF() {
zipFs.root.addHttpContent(FILENAME, URL);
}
function create_zip(){
zipPDF();
}
var btn = document.getElementById('button');
btn.addEventListener("click", create_zip, false);
</script>
jsfiddle
Related
I am creating an online HTML form that gives people the option to upload a file. I am using google sheets to collect the data so I am using their google scripts feature. When I run my code everything works, meaning I get data inserted into cells, but not the file upload. Here is my Google Scripts code for the file upload:
function doGet(request) {
return HtmlService.createTemplateFromFile('Index')
.evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function uploadFiles(data){
var folder = DriveApp.getFolderById('1pp1ELzGa2fZqU4IHAasZMHsmYx19pnYv');
var createFile = folder.createFile(data.image);
return createFile.getUrl();
}
From what I can tell the problem is at the data.image. This is where I am trying to retrieve my image so I can upload it into the folder. It must be that uploadFiles(data) is not properly bringing in data.
Here is the HTML and JavaScript:
<form id="myForm" onsubmit="handleFormSubmit(this)">
<h1 class="h4 mb-4 text-center" style="text-align:center"> <center>File Upload Testing</center></h1>
<table>
<tr>
<td colspan="11"><input type="file" id="image"></td>
</tr>
<input type="hidden" id="fileURL" name="fileURL">
</table>
<button type="submit" class="button button1" id="submitBtn">Submit</button>
</form>
<script>
document.getElementById('submitBtn').addEventListener('click',
function(e){
google.script.run.withSuccessHandler(onSuccess).uploadFiles(this.parentNode);;}
)
function onSuccess(data){
document.getElementById("fileURL").value = data;
}
</script>
I have a feeling that the e parameter is not retrieving the data above, however I don't really understand how it works. It could also be this.parentNode that's not grabbing the fike.
I am using the onSuccess function to retrieve the link so I can put it into my google sheet for quick access.
This is the error I receive;
Here is a link to the google sheet. To reach google scripts go to 'Tools -> Script Editor'.
https://docs.google.com/spreadsheets/d/16w8uB4OZHCeD7cvlrUv5GHP72CWxQhO1AAkF9MMSpoE/edit?usp=sharing
Here is another technique I attempted to use:
Javascript:
function uploadthis(fileForm){
const file = fileForm.image.files[0];
const fr = new FileReader();
fr.onload = function(e) {
const obj = {
// filename: file.name
mimeType: file.type,
bytes: [...new Int8Array(e.target.result)]
};
google.script.run.withSuccessHandler((e) => console.log(e)).uploadFiles(obj);
};
fr.readAsArrayBuffer(file);
}
Google Script:
function uploadFiles(data){
var file = Utilities.newBlob(data.bytes, data.mimeType); // Modified
var folder = DriveApp.getFolderById('1pp1ELzGa2fZqU4IHAasZMHsmYx19pnYv');
var createFile = folder.createFile(file);
return createFile.getId(); // Added
}
Thank you!
I am trying to set up a way to upload image files into a google drive. It will create a folder using a timeid and place the image inside the folder it created. I am having trouble calling out the image file. This is how I am attempting this, the folder gets created but no image.
Please ignore any missing var for the timeid variable. This is working fine.
Error given:
ReferenceError: imgInp is not defined
Thank you in advance for your help!
Code.gs
var day = d.getDate();
var month = d.getUTCMonth();
var hour = d.getHours();
var minutes = d.getMinutes();
var realmonth = month+1;
var timeid = String(year)+"-"+String(realmonth)+"-"+String(day)+"-"+String(hour)+"-"+String(minutes);
var foldername=timeid;
var parentFolder=DriveApp.getFolderById("##############");
function upload(){
var newFolder=parentFolder.createFolder(timeid);
var folderidlookup = newFolder.getId();
var destination = DriveApp.getFolderById(folderidlookup);
var imgf = imgInp;
var contentType = 'image/jpeg';
var imgf = imgf.getAs(contentType);
destination.createFile(imgf)
}
Html
<form>
<div class="file-field input-field">
<div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
<input type="file" name="imgInp" id="imgInp" onchange="loadFile(event)">
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path">
</div>
</div>
</form>
<button class="btn waves-effect waves-light" type="submit" name="action" id ="button">Submit
<i class="material-icons right">send</i>
</button>
JS
<script>
document.getElementById("button").addEventListener("click",upload);
function upload(){
google.script.run.upload();
}
</script>
The error you're getting is because you're trying to use a imgInp variable which you don't have it defined in any part of the code. You can get the blob file from the input, convert it to a binary array string, pass it to the server-side and finally use it to create your blob and the given Drive file, for this I used the code from this answer.
Using the examples for how to work with forms and success and failure handlers from the HTML Service guide, I put together the below code which worked successfully uploading the given image:
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<div class="file-field input-field">
<div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
<input type="file" name="imgInp" id="imgInp">
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path">
</div>
</div>
<button class="btn waves-effect waves-light" name="action" id="button">Submit
<i class="material-icons right">send</i>
</button>
</form>
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
// Add event listeners
window.addEventListener('load', preventFormSubmit);
document.getElementById("button").addEventListener("click", upload);
// Handler function
function logger(e) {
console.log(e)
}
async function upload() {
// Get all the file data
let file = document.querySelector('input[type=file]').files[0];
// Get binary content, we have to wait because it returns a promise
let fileBuffer = await file.arrayBuffer();
// Get the file content as binary and then convert it to string
const data = (new Uint8Array(fileBuffer)).toString();
// Pass the binary array string to uploadG funciton on code.gs
google.script.run.withFailureHandler(logger).withSuccessHandler(logger).uploadG(data);
}
</script>
</body>
</html>
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function uploadG(imgInp){
var parentFolder=DriveApp.getFolderById("[FOLER-ID]");
var newFolder = parentFolder.createFolder('test webApp');
var folderidlookup = newFolder.getId();
var destination = DriveApp.getFolderById(folderidlookup);
var contentType = 'image/jpeg';
// Convert the binary array string to array and use it to create the Blob
var blob = Utilities.newBlob(JSON.parse("[" + imgInp + "]"), contentType);
blob = blob.getAs(contentType);
destination.createFile(blob)
return 'Filed uploaded!';
}
File Upload Dialog
Run upLoadMyDialog() from script editor to get it started. The select file and click upload.
function fileUpload(obj) {
var d=new Date();
var ts=Utilities.formatDate(d, Session.getScriptTimeZone(), "yyyy-MM-dd-HH-mm");
var folder=DriveApp.getFolderById("****** Enter FolderId *******");
var file=folder.createFile(obj.file1).setName(ts);
}
function uploadMyDialog() {
var ss=SpreadsheetApp.getActive();
var html='<form><input type="file" name="file1"/><br /><input type="button" value="Upload" onClick="google.script.run.fileUpload(this.parentNode);" /></form>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}
With eventListener:
function uploadMyDialog() {
var ss=SpreadsheetApp.getActive();
var html='<form id="f1"><input type="file" name="file1"/><br /><input type="button" value="Upload" id="btn1" /></form>';
html+='<script>window.onload=function(){document.getElementById("btn1").addEventListener("click",function(){google.script.run.fileUpload(document.getElementById("f1"))})}</script>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}
I have a Html form that has a button capable of generating a XML file and downloading it to the users computers.
This is my XML.js file that writes all xml information and then donwloads the file to the user computer.
function downloadData(contentType,data,filename){
"use strict";
var link=document.createElement("A");
link.setAttribute("href",encodeURI("data:"+contentType+","+data));
link.setAttribute("style","display:none");
link.setAttribute("download",filename);
document.body.appendChild(link); //needed for firefox
console.log(link.outerHTML);
link.click();
setTimeout(function(){
document.body.removeChild(link);
},1000);
}
Function that gets the answers from the form
function fromToXml(form){
"use strict";
var xmldata=['<?xml version="1.0" encoding="UTF-8"?>'];
var inputs=form.elements;
xmldata.push("<AssetInfo>");
// file name*****************************
for(var i=0;i<inputs.length;i++){
if(inputs[i].value){
xmldata.push(" <customMetaData>");
xmldata.push(" <key>"+inputs[i].placeholder+"</key>");
xmldata.push(" <value>"+inputs[i].value+"</value>");
xmldata.push(" </customMetaData>");
}
}
xmldata.push("</AssetInfo>");
return xmldata.join("\n");
}
function download(frm){
"use strict";
var data=fromToXml(frm);
console.log(data);
// file name
downloadData("text/xml",data,"hello.xml");
}
HTML Button that calls the funtion inside XML.js
<button class="button" type="button" onclick="download(this.form)"
id="input">GerarXML</button>
HTML Button that asks the user to select a file
<input type="file" id="fileinput" nwdirectory multiple />
Need a back-end service in php that reads the file name and then store it in variable, and when generate the xml call the same variable.
I have an input tag:
<input type="file" id="fileUpload" accept=".csv"/>
that gets a csv file from the user. I then store the file into a variable as such:
const csvFile = document.getElementById('fileUpload');
How can I get the contents of the file into one big string if possible?
You can use the FileReader to read files.
<input type="file" id="fileUpload" accept=".csv" onchange="open(event)" />
<script>
var open = function(event) {
var input = event.target.files[0]
var readerObj = new FileReader()
readerObj.onload = function() {
var fileText = readerObj.result
//do something with fileText here....
}
readerObj.readAsText(input)
}
</script>
I'm trying to display a shape file from Brazil on my leaflet map, this shape file is inside a .zip that contains: .dbf, .prj, .sbn, .sbx, .shp and .shx files. To do that, I'm using: https://github.com/calvinmetcalf/leaflet.shapefile
I have the .zip file at my local computer so I simply made:
HTML
<button ng-click="addShape()"> Brasil Shape File </button>
JS
var mymap = L.map('mapid').setView([-12.85, -50.09], 4);
$scope.addShape = function () {
var shpfile = new L.Shapefile('scripts/ShapeFiles/Brasil.zip');
shpfile.addTo(mymap);
}
Now I want to make the user upload the .zip to show it on the map exactly like whats happening here:
http://leaflet.calvinmetcalf.com/#3/32.69/10.55
But I can't figure this out... All I have found on the internet is posting the .zip file to an url. I need to use the file right after the user "uploaded" it to the browser.
On the code bellow the user can upload some file and POST it, I tried to console.log the supposed objects that contains the .zip file before sending it but I couldn't find it inside the objects:
HTML
<body ng-controller="FileUploadCtrl">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" ng-model-instant id="fileToUpload" multiple onchange="angular.element(this).scope().setFiles(this)" />
</div>
<input type="button" ng-click="uploadFile()" value="Upload" />
</body>
JS
scope.setFiles = function(element) {
scope.$apply(function(scope) {
console.log('files:', element.files);
// Turn the FileList object into an Array
scope.files = []
for (var i = 0; i < element.files.length; i++) {
scope.files.push(element.files[i])
}
scope.progressVisible = false
});
};
scope.uploadFile = function() {
var fd = new FormData()
for (var i in scope.files) {
fd.append("uploadedFile", scope.files[i])
}
var xhr = new XMLHttpRequest()
xhr.upload.addEventListener("progress", uploadProgress, false)
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.addEventListener("abort", uploadCanceled, false)
xhr.open("POST", "/fileupload")
scope.progressVisible = true
xhr.send(fd)
}
source fiddle: danielzen
On this exemple, inside the functions 'setFiles' and 'uploadFile', when I console.log(fd) I get: fd: [object FormData] and console.log(element.files):
element.files[0] File {name: "Brasil (1).zip", lastModified: 1492436239000, lastModifiedDate: Mon Apr 17 2017 10:37:19 GMT-0300 (BRT), webkitRelativePath: "", size: 5988862…}
But I can't find the original .zip file that was uploaded, maybe because this is not the right way to do it...
If someone knows a way to get this .zip file or have access to this example source and can share with me I'll be very thankful.
I managed to solve this by using an arrayBuffer for the shapefile as it is specified here. I figured that out reading about this issue.
Here is my code:
HTML
<div id="mapid" style="width: 800px;float: left;">
</div>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
JS
function loadFile() {
input = document.getElementById('fileinput');
if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receiveBinary;
fr.readAsArrayBuffer(file);
}
function receiveBinary() {
result = fr.result
var shpfile = new L.Shapefile(result);
shpfile.addTo(mymap);
}
}
I use angular 12... and I can upload file with Shapefile.js https://github.com/calvinmetcalf/shapefile-js
You can see my code in https://gitlab.com/-/snippets/2141645