So I am trying to use the SheetJS javascript to read in some excel files. I download the SheetJS and I have copied the xlsx.full.min.js in same directory as my html file. However, I do not get it to work. So I tried the code below. The problem is that it does not reach the alert('finished reading'); line. So I do not know if there was a problem reading the source file or what the problem exactly is. I hope somebody can help me with this! Thanks!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
</style>
</head>
<body>
<p><input type="file" name="xlfile" id="xlf" /> ... or click here to select a file</p>
<script src="xlsx.full.min.js"></script>
<script>
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
alert(data);
var result;
alert('reading now');
var workbook = XLSX.read(data, { type: 'binary' });
alert('finished reading');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//Get the first column first cell value
alert(result[0].Column1);
};
reader.readAsArrayBuffer(f);
}
}
var xlf = document.getElementById('xlf');
if(xlf.addEventListener) xlf.addEventListener('change', handleFile, false);
</script>
</body>
</html>
Related
i am currently working on my upload file page and below is the upload function on the client side
and i want the client to check the image first before upload to the server
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Testing</title>
</head>
<body>
<h1>Upload img</h1>
<form action="/upload" method="post" enctype="multipart/form-data" id="form"></form>
<button id="submit" onclick="upload()">Submit</button>
<!-- <script src="main.js"></script> -->
<script>
function multipleImageUpload() {
const input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("multiple", "multiple");
const preview = document.createElement("div");
preview.setAttribute("id", "preview");
document.body.appendChild(preview);
input.addEventListener("change", (event) => {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const img = document.createElement("img");
img.setAttribute("src", URL.createObjectURL(files[i]));
const removeBtn = document.createElement("button");
removeBtn.innerHTML = "Remove";
removeBtn.addEventListener("click", () => {
preview.removeChild(img);
preview.removeChild(removeBtn);
});
preview.appendChild(img);
preview.appendChild(removeBtn);
}
});
document.getElementById('form').append(input);
}
multipleImageUpload()
function upload(){
const imgs = preview.querySelectorAll("img");
const files = [];
for (let i = 0; i < imgs.length; i++) {
files.push(imgs[i].src);
}
console.log(files);
//submit
// document.getElementById('form').submit()
}
</script>
</body>
</html>
inside the files is blob file link
how to read these array of blob to behave as File
then inlude it inside my form
when i click sumit these blob file must be submitted too in node server
My Server
var express = require('express');
var router = express.Router();
const multer = require('multer')
const upload = multer({
dest:'uploads/'
})
const cpUpload = upload.fields([{name:'files'}])
router.get('/', function(req, res, next) {
res.render('upload/index');
});
router.post('/', cpUpload,(req, res, next)=>{
console.log(req.files);
})
module.exports = router;
i tried converting to files these blob as new File() method but it didnt work because i have to read the blob as file first to add parameter in new File() even if i input it in the File,
i have to put them in the new FormData()
i dont know how that work
when log the form data theres no values
I'm facing issue. single and multiple file uploaded file. Then multiple file upload successfully but when single file one by one upload then last one upload other are override by last one. Please help me to find out this problem solution. As you can see below code it's work properly for multiple upload file and send data by ajax then get array value all images but when upload single upload one by one then last one image data get only in ajax data in. please help me to provide me solution.
index.php
`
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
</style>
<body>
<form id="myForm" method="post">
<input type="file" id="files" class="file_uploader_file" name="files[]" multiple="true" accept="image/*" />
<p class="validateError" id="imgerror" style="color:red;display:none;">Please select your design.</p>
<input type="button" id="fees_stream_submit1" name="submit">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
(function () {
$(document).on('click', '#fees_stream_submit1', function (e) {
var myfiles = document.getElementById("files");
// var myfiles = $('#files').val();
var files = myfiles.files;
var form = new FormData();
alert(files.length);
for (i = 0; i < files.length; i++) {
form.append('file' + i, files[i]);
}
$.ajax({
url: "fileuploadmultidata.php",
type: "POST",
data: form,
contentType: false,
processData: false,
success: function (result) {
// alert(result);
}
});
});
})();
$(document).ready(function () {
var imgCnt = 0;
var onebyoneImg = [];
var countImg = 1;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
// var f = new File([""], files[i]);
var fileReader = new FileReader();
fileReader.onload = (function (e) {
imgCnt++;
alert(imgCnt);
var file = e.target;
$("<span class='pip'><div class=\"file_uploaded_view img-thumb-wrapper image-preview-height\">" +
"<img class=\"img-thumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\" style='heigh:100px;width:100px'/>" +
"<br/><span class='remove'><i class='fa fa-trash'></i></span></span>" +
"</div>").insertAfter("#files");
$(".remove").click(function () {
$(this).parent(".img-thumb-wrapper").remove();
imgCnt--;
});
});
fileReader.readAsDataURL(f);
}
console.log(f);
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
</body>
</html>
`
**fileuploadmultidata.php**
`<?php
echo "<pre>";
print_r($_FILES);die();
?>`
The behaviors of file uploading will be like that only see https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
To achieve your requirement you need to store file values in variable and use.
var storeMultiFiles = [];
var file = $(file_id)[0].files;
for(var l=0; l<file.length; l++){
var fileData = file[l];
(function(file) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(oFREvent){
storeMultiFiles.push(oFREvent.target.result)
};
})(fileData);
}
Use files details using "storeMultiFiles" for show, save, update and delete for selected.
I am facing this problem, and i cannot figure it out. Its simple thing, i need to include my js file into a head. But in my page I've got error Uncaught SyntaxError: Unexpected token '<' in ShopData.js:1 . So I've checked that file in chrome inspector, and i see that there is no JS content inside of it. It basically clone the html file and include it as js. How this can even happen and what is the solution? In ShopData.js is pure JS content, no includes or something. I've already checked permissions for that files and set it to read/write but no result, whole page is in domain hosting. Thanks for any advice.
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="ShopData.js"></script>
</head>
JS File:
var ShopID = 0;
var Name = "";
var City = "";
var Street = "";
var PostCode = "";
var State = "CZ";
var Longitude = "";
var Lattitude = "";
var Email = "";
var Telephone = "";
var Tittle = "";
var Description = "";
var Keywords = "";
var Barbers;
var OpeningHours;
var ItemTypes;
var Items;
let ShopData = {};
jQuery.ajax({
type: "GET",
url: "https://example.com/",
dataType: "json",
success: function(response) {
console.log(response);
}
});
Screenshot of response
This file isn't valid JavaScript so it will give that error:
https://barber.minuto.cz/web/ShopData.js
Also it seems to give that response no matter which URL you type in:
https://barber.minuto.cz/web/asdfasdf
Also you may want to make it so everyone can't login here since it is out in public now:
https://barber.minuto.cz
I am actually using this library: https://github.com/SheetJS/js-xlsx.
I used it to create and download an XLSX file that extracts a table from my website. This does work pretty well, but I am trying to do something more complicated now.
I am trying to download all my tables at the same time, which means downloading multiple XLSX files. It does works with my actual code :
function saveAll(dataAll){
for (let i=0;i<dataAll.length;++i) {
let ws_name = "SheetJS";
let data = dataAll[i];
let wb = new Workbook();
console.log(data);
let ws = sheet_from_array_of_arrays(data.content, null, data.mois, data.annee);
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});
saveAs(new Blob([s2ab(wbout)],{type: "application/octet-stream"}), data.prenom_nom + " PVA " + data.mois + " " + data.annee + ".xlsx");
}
}
Now i'd like to download all those xlsx files into an unique ZIP or tar.gz file, but i am kinda stuck. I tryed to use the zip.js library, but without success.
My dataAll parameter is array of objects, and each object contains .content which is a matrix, and some other parameters used on the file name.
How can I manage to download all these xlsx files in only one archive, instead of downloading them one by one?
You can try this
var zip = new JSZip();
for(var i=1;i<3;i++)
{
var workbook = XLSX.utils.book_new();
var ws1 = XLSX.utils.table_to_sheet(document.getElementById('tbl'+i));
XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1");
let wbout = XLSX.write(workbook, {bookType: 'xlsx', bookSST: true, type: 'binary'});
zip.file("shubham"+i+".xlsx", wbout, {binary: true});
}
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "example.zip");
});
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width" , initial-scale=1, shrink>
<meta name="theme-color" content="#000000">
<title>ES6</title>
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.0/jszip.min.js"></script>
</head>
<body>
<table id="tbl1">
<tr><td>Name</td><td>Age</td></tr>
<tr><td>Shubham</td><td>22</td></tr>
</table>
<table id="tbl2">
<tr><td>Name</td><td>Age</td></tr>
<tr><td>Shubham</td><td>22</td></tr>
</table>
</body>
<script>
</script>
</html>
I am using this code to download these Images but This programming making a txt files with these names and with type jpeg . why this is happening ? this programm is not working on chrome due to cross site but on firefox in zip file empty txt files are.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js" type="text/javascript">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip-utils/0.0.2/jszip-utils.min.js" type="text/javascript">
</script>
<script>
var urls = [
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0397.jpg",
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0398.jpg",
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0488.jpg"
];
var nombre = "Zip_img";
//The function is called
compressed_img(urls, nombre);
function compressed_img(urls, nombre) {
var zip = new JSZip();
var count = 0;
var name = nombre + ".zip";
urls.forEach(function(url) {
JSZipUtils.getBinaryContent(url, function(err, data) {
if (err) {
throw err;
}
zip.file(url, data, {
binary: true
});
count++;
if (count == urls.length) {
zip.generateAsync({
type: 'blob'
}).then(function(content) {
saveAs(content, name);
});
}
});
});
}
</script>
</body>
</html>