angular2 : read a file from local machine - javascript

Hi I am new to JavaScript and Angular 2.
I want to read a text file from local machine and show the content on page. I have the file in assets folder. How can I read it using typescript?
Thanks in advance :)
I tried passing file path as "e" but the error i am getting is on files[0]. If I remove files[0] error I am getting is parameter 1 is not of type 'Blob'.
private readSingleFile(e) {
var fileName = e.files[0];
console.log(fileName);
if (!fileName) {
return;
}
var reader = new FileReader();
reader.onload = file => {
var contents: any = file.target;
this.text = contents.result;
};
reader.readAsText(fileName);
console.log(reader.readAsText(fileName))
}

instead of e.files[0]
try
e.target.files[0]
code snippet:
var fileName = e.target.files[0];
<input type='file' (change)='readSingleFile($event)'>

Thanks everyone for the responses.
Finally i read the files using 'ng2-file-upload' and uploaded them to server also.

Related

Uncaught TypeError: root is undefined papaparse

I have a problem with papaparse in my code, I try to parse a string but is giving me this error:
Uncaught TypeError: root is undefined"
the code is like:
import * as Papa from "../file/papaparse/papaparse.js";
input.onchange = e => {
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = readerEvent => {
let imported = readerEvent.target.result;
let splittedimp = this.$Papa.parse(imported, {
"header": true
})
console.log(splittedimp);
}
}
the input.onchange is inside an async function.
any idea why this error?
The error happen in papaparse file, line 25:
root.Papa = factory();
also i didn't use nodejs or jquery, i have simply downloaded the file and imported it into a folder in my project
The problem was that papaparse didn't like the import as. I have added the URL into the script in the HTML page connected to the JS page and now works fine.

React: Read Zip file using JSZip from the project directory

I am trying to read a zip file which has images from the project directory in React.
When I open the Zip file from <input type="file" />, it works by taking the event.target.files[0] .
But when I put that same file in react project and then try to open it by giving a path , it doesnt work.
Example : "./test.zip"
My current code:
let jsZip = new JSZip();
jsZip.loadAsync("./test.zip").then(function (zip) {
let imagess = [];
Object.keys(zip.files).forEach(function (filename) {
zip.files[filename].async("base64").then(function (fileData) {
const image = document.createElement("img");
image.src = "data:image/*;base64," + fileData;
document.querySelector(".unziped-container").appendChild(image);
});
});
});
I have been stuck on this for hours and the documentation is not helping either.
Any help is appreciated.
Anyone coming across this can use JSZip-utils and write the following code
JSZipUtils.getBinaryContent("../path/file.zip", function (err, data) {
if (err) {
throw err;
}
const jsZip = new JSZip();
jsZip.loadAsync(data).then(function (zip) {
Object.keys(zip.files).forEach(function (filename) {
zip.files[filename].async("base64").then(function (fileData) {
const image = document.createElement("img");
image.src = "data:image/*;base64," + fileData;
const unziped = document.querySelector(".unziped-container");
unziped.appendChild(image);
});
});
});
});
the documentation seems pretty clear: the first argument to loadAsync is the zip file data, but you're passing it a string.
(and what you're tring to do won't work anyway. your React code is running in the browser and has no knowledge of filesystem paths or filenames.)

How to properly read all file types with react js and add to IPFS in browser

enter image description here
I am trying to read a file (which can be anything like video, image , text ) with react .
I want to add data in the IPFS through Node JS. In normal case(which means when i m only writing in js) I would do it like this :
const data = await fs.readFile(file_path)
console.log(data)
const filesAdded = await nodeDialer.add({
path:file_path,
content:data,
})
console.log(filesAdded)
THe files would be added easily(any type of file).
I tried fs and found out it only works in the node side not on the react side.
and whereever i looked they were using some readastext functions for .txt file or .csv file.
So a proper solution, I couldn't find.
I solved it with this:
Created a event handler for file upload :
captureFile(event){
const file = event.target.files[0]
this.setState({ file_path : file})
console.log('--------------', this.state.file_path)
const reader = new window.FileReader()
reader.readAsArrayBuffer(file)
reader.onloadend = () => {
this.setState({ buffer: Buffer(reader.result) })
console.log('buffer --- ', this.state.buffer)
console.log('path --- ', this.state.file_path.name)
}
}
then I add the file in IPFS with :
const filesAdded = await node.add({
path: this.state.file_path.name ,
content:this.state.buffer
})

Convert a collectionFS file from filesystem to gridFS on serverside

In our meteor app, the client will upload some files using collectionFS-filesystem which i store it to an uploads folders in root directory of my app.
//My CFS uploads collection
uploads = new FS.Collection("uploads", {
stores: [new FS.Store.FileSystem("uploads", {path: "~/uploads"})]
});
Later, i want to save the files to the database using collectionFS-gridFS.
//My CFS grid collection
files = new FS.Collection("files", {
stores: [new FS.Store.GridFS("files")]
});
How do i read the data from the file on server so that i can store the file to db? Can i use the file from the CFS-filesystem collection to convert it to CFS-gridFS file in anyway?
Thanks in advance.
I had accept the answer by #perusopersonale. However, below is my approach which i used to achieve this, based on documentation from here and here
uploads.find(document_id).forEach(function (fileObj) {
var type = fileObj.type();
var name = fileObj.name();
var readStream = fileObj.createReadStream(fileObj.collectionName);
var newFile = new FS.File();
newFile.attachData(readStream, {type: type});
newFile.name(name);
files.insert(newFile);
});
I don't understand why you want to use both. However I have to implement something similar (read from a cfs filesystem, do something and then reinsert in another db), here a version modified that should accomplish what you are triyng to do:
var fileObj = uploads.findOne(objId);
var newName = "newfilename"; //file name
//fileObj.copies.uploads.key contains the filename for store :"uploads"
fs.readFile( "~/uploads/"+fileObj.copies.uploads.key, function (err, data) {
var newFile = new FS.File();
newFile.attachData(data,{type: 'application/octet-stream'}, function(error){
newFile.name( newName);
file.insert(newFile);
});
});

How to Zip files using jszip library

Am working on an offline application using HTML5 and jquery for mobile. i want to back up files from the local storage using jszip. below is a code snippet of what i have done...
if (localStorageKeys.length > 0) {
for (var i = 0; i < localStorageKeys.length; i++) {
var key = localStorageKeys[i];
if (key.search(_instrumentId) != -1) {
var data = localStorage.getItem(localStorageKeys[i])
var zip = new JSZip();
zip.file(localStorageKeys[i] + ".txt", data);
var datafile = document.getElementById('backupData');
datafile.download = "DataFiles.zip";
datafile.href = window.URL.createObjectURL(zip.generate({ type: "blob" }));
}
else {
}
}
}
in the code above am looping through the localstorage content and saving ezch file in a text format. the challenge that am facing is how to create several text files inside DataFiles.zip as currently am only able to create one text file inside the zipped folder. Am new to javascript so bare with any ambiguity in my question.
thanks in advance.
Just keep calling zip.file().
Look at the example from their documentation page (comments mine):
var zip = new JSZip();
// Add a text file with the contents "Hello World\n"
zip.file("Hello.txt", "Hello World\n");
// Add a another text file with the contents "Goodbye, cruel world\n"
zip.file("Goodbye.txt", "Goodbye, cruel world\n");
// Add a folder named "images"
var img = zip.folder("images");
// Add a file named "smile.gif" to that folder, from some Base64 data
img.file("smile.gif", imgData, {base64: true});
zip.generateAsync({type:"base64"}).then(function (content) {
location.href="data:application/zip;base64," + content;
});
The important thing is to understand the code you've written - learn what each line does. If you do this, you'd realize that you just need to call zip.file() again to add another file.
Adding to #Jonathon Reinhart answer,
You could also set both file name and path at the same time
// create a file and a folder
zip.file("nested/hello.txt", "Hello World\n");
// same as
zip.folder("nested").file("hello.txt", "Hello World\n");
If you receive a list of files ( from ui or array or whatever ) you can make a compress before and then archive. The code is something like this:
function upload(files){
var zip = new JSZip();
let archive = zip.folder("test");
files.map(function(file){
files.file(file.name, file.raw, {base64: true});
}.bind(this));
return archive.generateAsync({
type: "blob",
compression: "DEFLATE",
compressionOptions: {
level: 6
}
}).then(function(content){
// send to server or whatever operation
});
}
this worked for me at multiple json files. Maybe it helps.
In case you want to zip files and need a base64 output, you can use the below code-
import * as JSZip from 'jszip'
var zip = new JSZip();
zip.file("Hello.json", this.fileContent);
zip.generateAsync({ type: "base64" }).then(function (content) {
const base64Data = content

Categories