Hi i want to open excel file with xlsx extension with xlsx.js library.
I can open file by html input but i want to open it by using file path.
I have this code extracted from xlsx.js demo:
function handleFile(e) {
rABS = false;
use_worker = false;
console.log(e);
var files = e.target.files;
var f = files[0]; {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
if (typeof console !== 'undefined')
console.log("onload", new Date(), rABS, use_worker);
var data = e.target.result;
console.log("target result >>>>>>>>> " + e.target.result);
if (use_worker) {
xw(data, process_wb);
} else {
var wb;
if (rABS) {
wb = X.read(data, {
type : 'binary'
});
} else {
var arr = fixdata(data);
wb = X.read(btoa(arr), {
type : 'base64'
});
}
process_wb(wb);
}
};
if (rABS)
reader.readAsBinaryString(f);
else
reader.readAsArrayBuffer(f);
}
}
I want something like this:
var file = new File([""],"C:\\Users\\PalFS\\Downloads\\Fiverr_Example_List (1).xlsx");
var data = file;
How to do this or how can i convert this file into arraybuffer like it is returned from, var data = e.target.result;.
Thanks
You could use --allow-file-access-from-files flag at chrome, chromium with XMLHttpRequest , .responseType set to "arraybuffer" to retrieve .xlsx file from local filesystem as ArrayBuffer; set new File() data to returned ArrayBuffer. Second parameter at new File() constructor should set the .name property of created file.
Launch /path/to/chrome --allow-file-access-from-files
var request = new XMLHttpRequest();
// may be necessary to escape path string?
request.open("GET", "C:\\Users\\PalFS\\Downloads\\Fiverr_Example_List (1).xlsx");
request.responseType = "arraybuffer";
request.onload = function () {
// this.response should be `ArrayBuffer` of `.xlsx` file
var file = new File(this.response, "Fiverr_Example_List.xlsx");
// do stuff with `file`
};
request.send();
Related
i know there are tonnes of solutions regarding this but no answers for pre-selected excel file.
var ExcelToJSON = function() {
this.parseExcel = function( file ) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
jQuery('#xlx_json').val(json_object);
})
};
reader.readAsBinaryString(file);
};
};
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
Here instead of browsing a file, i want to open the file '../img/file.xlsx' and convert it into an object. What is the best way to do it?
Did you try using xlsx?
install using
npm install xlsx
to read file,
const reader = require('xlsx')
const file = reader.readFile('../img/file.xlsx')
Hello! I'am trying to make it work a function called loadDocument, who need a url of the loaded files from the user local computer to work. I'm writing an API to load document from local user computer, and show it on a web reader.
This is my upload button :
<input type="file" id="input" onchange="module.onLoadSelection();" alt="Browse" name="upload"/>
This is my function without fileReader :
var onLoadSelection = function () {
var select = document.getElementById('input');
if (select && select.value) {
var id= '';
var url = select.files.item(0).name;
module.loadDocument(url,id);
}
};
This is my function with fileReader :
var loadTest = function (input) {
var file = document.querySelector('input[type=file]').files[0];
console.log("file loaded! ->", file); // i can read the obj of my file
var reader = new FileReader();
var id = ''; // don't need rightnow
var url = reader.readAsDataURL(file);
console.log("url :", url); // show me undefined....
module.loadDocument(url,id);
}
What i am trying is to get the url of the loaded file from user computer to get my function loadDocument working. She need a url parameter to work.
loadDocument is an API function, i assume i can't get the filepath of my user due to security reason.
What do i need to change/update on my loadDocument(); function to work?
Edit : In fact, nothing to change. The correct way to read my file was :
<input type="file" id="input" onchange="module.onLoadSelection(this.files);" alt="Browse" name="upload"/>
var onLoadSelection = function (files) {
if (files && files.length == 1) {
var id = '';
var url = URL.createObjectURL(files[0]);
module.loadDocument(url,id);
}
};
Don't use a FileReader at all.
When you want to display a File (or a Blob) that is in the browser's memory or on user's disk, then all you need is to generate an URL that do point to this memory slot.
That's exactly what URL.createObjectURL(blob) does: it returns a Blob URI (blob://) that points to the data either in memory or on the disk, acting exactly as a simple pointer.
This method has various advantages over the FileReader.readAsDataURL() method. To name a few:
Store the data in memory only once, when FileReader would need it at reading, then generate a copy as an base64 encoded, and an other one at displaying...
Synchronous. Since all it does is to generate a pointer, no need to make it async.
Cleaner code.
const module = {
loadDocument: (url) => {
document.body.append(
Object.assign(
document.createElement('iframe'),
{ src: url }
)
)
}
};
document.querySelector('input[type=file]').addEventListener('input', function (evt) {
var file = this.files[0];
var url = URL.createObjectURL(file);
module.loadDocument(url);
});
<input type="file">
function PreviewFiles(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//alert(e.target.result);
$('#pclogo').prop('src', e.target.result)
.width(200)
.height(200);
var base64result = e.target.result.split(',')[1];
$('input[name="logo"]').val(base64result);
};
reader.readAsDataURL(input.files[0]);
}
}
File objects have a readAsDataURL method.
Use that.
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
doSomethingWithAUrl(reader.result);
}, false);
if (file) {
reader.readAsDataURL(file);
}
Using the sapui5 uploadcollection to upload files in the frontend and then sending them through ajax with a post request...
I need to know how to convert te returned object from the uploadcollection control into a xstring, so then I can send that xstring (that contains the file content) To a sap gateway by using ajax post method.
Any idea how could I do this?
Right now I'm sending files by using the uploadcollection, once I upload an attachment, the control returns an object that represents the file content.
I'm trying to make this object a xstring by using filereader:
//obtiene archivo
var file = files[i];
//Convierte archivo en binario
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
var base64 = btoa(binaryString);
var base64file;
if(typeof base64file == "undefined" || typeof base64file == null){
base64file = base64;
}else{
base64file = base64file +'new'+base64;
}
};
reader.readAsBinaryString(file);
console.log(file)
But this work only with files of type image, the others like pdf, .doc etc etc give the following error when I try to send them with ajax.
"The Data Services Request could not be understood due to malformed syntax".
Any idea how can I send convert these files into a xstring data?
Take a look at this example. Hope this helps.
View
<u:FileUploader change="onChange" fileType="pdf" mimeType="pdf" buttonText="Upload" />
Controller
convertBinaryToHex: function(buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), function(x) {
return ("00" + x.toString(16)).slice(-2);
}).join("");
},
onChange: function(oEvent){
var that = this;
var reader = new FileReader();
var file = oEvent.getParameter("files")[0];
reader.onload = function(e) {
var raw = e.target.result;
var hexString = that.convertBinaryToHex(raw).toUpperCase();
// DO YOUR THING HERE
};
reader.onerror = function() {
sap.m.MessageToast.show("Error occured when uploading file");
};
reader.readAsArrayBuffer(file);
},
I figured it out by filling an array everytime that a file was uploaded through the control,
change: function(oEvent) {
//Get file content
file = oEvent.getParameter("files")[0];
//Prepare data for slug
fixname = file.name;
filename = fixname.substring(0, fixname.indexOf("."));
extension = fixname.substring(fixname.indexOf(".") + 1);
//fill array with uploaded file
var fileData = {
file: file,
filename: filename,
extension: extension
}
fileArray.push(fileData);
},
and then I did a loop over that array to post every single file I keept there by using ajax method post.
$.each(fileArray, function(j, valor) {
//get file
file = fileArray[j].file;
//get file lenght
var numfiles = fileArray.length;
//Convert file to binary
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(evt) {
fileString = evt.target.result;
//get and make slug
filename = fileArray[j].filename;
extension = fileArray[j].extension;
slug = documento + '/' + filename + '/' + extension;
//User url service
var sUrlUpload = "sap url";
runs++;
//Post files
jQuery.ajax({});
}
});
I want to read a file from local storage and upload it via ajax. How is this done?
In most browsers, you can use FileReader to read data from file inputs. There are various functions for reading the data; this example uses the function that returns an ArrayBuffer containing all the bytes:
<script>
window.onload = function() {
document.getElementById('upload').onchange = function(e) {
var file = e.target.files[0];
var fileReader = new FileReader();
fileReader.onload = function(e) {
var bytes = e.target.result;
console.log(bytes);
};
fileReader.readAsArrayBuffer(file);
};
};
</script>
<input type = 'file' id = 'upload' />
I managed to figure it out. Here's the code for anyone interested.
var form = new FormData();
form.append("data", angular.toJson(message));
var bytes = new Uint8Array(audio.length); //audio is an IBuffer
var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(audio);
dataReader.readBytes(bytes);
dataReader.close();
var media = new Blob([bytes], { type: "application/octet-stream" }); //application/octet-stream or audio/mpeg?
form.append("attached_files", media, "recording-aac.caf");
return $http.post(AppSettings.baseUri + "api/sendmessage", form, { headers: { "Content-Type": undefined } });
I'm having trouble saving blob in IndexedDB, and only with blob.
If I save something else (like image as base64), everything works fine.
But with blob, there is simply empty object property saved.
Screenshot from console:
Code:
//prepared blob...
var openRequest = indexedDB.open("testDB",1);
openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("stash")) {
thisDB.createObjectStore("stash");
}
}
openRequest.onsuccess = function(e) {
db = e.target.result;
var transaction = db.transaction(["stash"],"readwrite");
var store = transaction.objectStore("stash");
var tID = Date.now();
var obj = {
bl:blob,
created:tID
}
console.log(obj);
//add it
var request = store.add(obj, tID);
request.onerror = function(e) {
console.log("Error",e.target.error.name);
}
request.onsuccess = function(e) {
console.log("success");
}
}
openRequest.onerror = function(e) {
//....
}
I also tried to save only blob (not wrapped as obj property), it's the same.
I can save blob to HDD, and if I console log my obj, I get:
So I guess, blob is valid, and problem is in adding it to indexedDB. I'm new to blob/indexedDB, and probably doing some noob mistake.
Can someone please advise, what am I doing wrong?
PS: no error messages at all
Very old question, but there is support now for saving Blobs in IndexedDb:
https://developers.google.com/web/updates/2014/07/Blob-support-for-IndexedDB-landed-on-Chrome-Dev
// Create an example Blob object
var blob = new Blob(['blob object'], {type: 'text/plain'});
try {
var store = db.transaction(['entries'], 'readwrite').objectStore('entries');
// Store the object
var req = store.put(blob, 'blob');
req.onerror = function(e) {
console.log(e);
};
req.onsuccess = function(event) {
console.log('Successfully stored a blob as Blob.');
};
} catch (e) {
var reader = new FileReader();
reader.onload = function(event) {
// After exception, you have to start over from getting transaction.
var store = db.transaction(['entries'], 'readwrite').objectStore('entries');
// Obtain DataURL string
var data = event.target.result;
var req = store.put(data, 'blob');
req.onerror = function(e) {
console.log(e);
};
req.onsuccess = function(event) {
console.log('Successfully stored a blob as String.');
};
};
// Convert Blob into DataURL string
reader.readAsDataURL(blob);
}
As of posting this, the referenced Document was last updated on: Last updated 2019-03-20 UTC.
You can convert Blob or File object to ArrayBuffer object or binarystring and then save it. Convert it back to Blob after you read from indexedDB.
//prepared blob...
blobToBlob2(blob, saveBlob2);
function blobToBlob2(blob, callback){
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = function(e) {
callback({
buffer: e.target.result,
type: blob.type
});
};
}
function blob2ToBlob(blob2){
return new Blob([blob2.buffer],{type:blob2.type});
}
function saveBlob2(blob2){
//..... code
var obj = {
bl:blob2,
created:tID
}
var request = store.add(obj, tID);
//..... code
}