Display shapeFile on leaflet map using an uploaded file.zip - javascript

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

Related

Google Scripts/HTML/JavaScript Upload File to Folder Error Argument cannot be null: blob

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!

How to get the text from a csv file in vanilla javascript

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>

FileReader onload not getting fired for second attempt in IE 11 after contents of the uploaded file is changed

FileReader onload not getting fired on second time when the same file still selected with IE11 but the contents of file has changed, it's getting fired all the time for FireFox,Chrome.
Operation Details
On First Click, its all okay for all browsers(but IE sometime still missing some words from file).
After that I changed the contents of the file.
And then I click second attempt to btnDownload, Firefox and Chrome still reading the updated contents. BUT IE DOES NOT WORK!
.html
<input type="file" id="fileSelect" style="" accept=".csv">
<a type="button" class="btn" id="btnDownload" onclick="csvDownload()"
download> CSV DOWNLOAD </a>
myjavascript.js
var fileInput = document.getElementById("fileSelect"); //<input type="file" id="fileSelect">
var result = "";
readFile = function() {
changeAPInfoName();
if (!isFileSupported()) {
console.log('The browser does not support the API.');
} else {
if (fileInput.files.length > 0) {
var reader = new FileReader();
reader.onload = function() {
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
}
reader.readAsText(fileInput.files[0]);
reader.onerror = function() {
console.log('The file cannot be read.'+fileInput.files[0].fileName);
};
}
// EVENT FOR DOWNLOAD BUTTON!!!!
function csvDownload(){
readFile();
// using ajax to sent info from files and get download file.
}
Please help me with following issue.
How can I get to the line in reader.onload method although file contents are changed. alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)"); .
Replace this
reader.onload = function() {
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
}
with
reader.addEventListener("load",function(){
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
});
I hope this is helpful. I was facing the same problem and I used this method and it worked
Example of working FileReader:
<html>
<head>
<script>
function read(){
//Select the element containing file
var file =document.querySelector('input[type=file]').files[0];
//create a FileReader
reader = new FileReader();
//add a listener
reader.addEventListener('load',function(){
alert(reader.result);
},false);
if(file){
//ReadFile
reader.readAsDataURL(file);//You can read it in many other forms
}
}
</script>
</head>
<body>
<input type="file" name="myFile" id="myFile" onchange="read()">
</body>
</html>
For more on FileReader check this document out : Link

How to zip a pdf or ppt file using zip.js?

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

get the data of uploaded file in javascript

I want to upload a csv file and process the data inside that file. What is the best method to do so? I prefer not to use php script. I did the following steps. But this method only returns the file name instead of file path.So i didnt get the desired output.
<form id='importPfForm'>
<input type='file' name='datafile' size='20'>
<input type='button' value='IMPORT' onclick='importPortfolioFunction()'/>
</form>
function importPortfolioFunction( arg ) {
var f = document.getElementById( 'importPfForm' );
var fileName= f.datafile.value;
}
So how can i get the data inside that file?
The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.
See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
In this example, the user selects an HTML file. It is displayed in the <textarea>.
<form enctype="multipart/form-data">
<input id="upload" type=file accept="text/html" name="files[]" size=30>
</form>
<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>
<script>
function handleFileSelect(evt) {
let files = evt.target.files; // FileList object
// use the 1st file from the list
let f = files[0];
let reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
jQuery( '#ms_word_filtered_html' ).val( e.target.result );
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
you can use the new HTML 5 file api to read file contents
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
but this won't work on every browser so you probably need a server side fallback.
The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.
function init() {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event) {
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
There exist some new tools on the blob itself that you can use to read the files content as a promise that makes you not have to use the legacy FileReader
// What you need to listen for on the file input
function fileInputChange (evt) {
for (let file of evt.target.files) {
read(file)
}
}
async function read(file) {
// Read the file as text
console.log(await file.text())
// Read the file as ArrayBuffer to handle binary data
console.log(new Uint8Array(await file.arrayBuffer()))
// Abuse response to read json data
console.log(await new Response(file).json())
// Read large data chunk by chunk
console.log(file.stream())
}
read(new File(['{"data": "abc"}'], 'sample.json'))
Try This
document.getElementById('myfile').addEventListener('change', function() {
var GetFile = new FileReader();
GetFile .onload=function(){
// DO Somthing
document.getElementById('output').value= GetFile.result;
}
GetFile.readAsText(this.files[0]);
})
<input type="file" id="myfile">
<textarea id="output" rows="4" cols="50"></textarea>
FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.

Categories