convert file to base64 in angular - javascript

i am new to angular and i want to convert files into base64 string. i try this and it gives base64 string but when i try to decode it using online tool it did not give correct result can anyone help me thank you.
can we convert pdf and word file into base64 or just images. with my code i successfully converted images but not any other file
my html code:
<input type="file" (change)="base($event)">
and my ts code:
base(event: { target: { files: any[]; }; }) {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
console.log(reader.result);
};
}

Your code works fine. Are you sure you are correctly getting the file object?
Below is the stackblitz demo of the same.
Also, it better to use promise while reading files. You can use below function to read a file. It takes file as input and resolves to base64 string.
private readBase64(file): Promise<any> {
const reader = new FileReader();
const future = new Promise((resolve, reject) => {
reader.addEventListener('load', function () {
resolve(reader.result);
}, false);
reader.addEventListener('error', function (event) {
reject(event);
}, false);
reader.readAsDataURL(file);
});
return future;
}
Call this function as below -
this.readBase64(file)
.then((data) => {
// your code
});

Related

Read uploaded JSON file in Angular

I am using the <p-fileUpload> from PrimeNG to upload a json file in my web-app. I want to read the json file, in the front-end, and change some values of a data table.
However, I have no idea how to parse the uploaded file as a json to a typescript object. Any ideas?
In the HTML file:
<p-fileUpload #ratingsUpload mode="basic" name="demo[]"
url="" accept=".json"
styleClass="p-button-raised"
[auto]="true" chooseLabel="Upload ratings"
(onUpload)="onRatingsUpload($event)"></p-fileUpload>
In the typescript file:
onRatingsUpload(event: any) {
console.log(event.files)
// TODO:
// data = JSON(event.files);
}
Edit: I can't get the event to fire. onRatingsUpload does not seem to be called...
You have to use FileReader:
const reader = new FileReader();
reader.onload = (event) => {
try {
var obj = JSON.parse((event.target.result) as string);
console.log('my json:', obj);
} catch (error) {
console.error(error);
}
};
reader.readAsText(file);
//You need to use FileReader
onFileChanged(event) {
this.selectedFile = event.target.files[0];
const fileReader = new FileReader();
fileReader.readAsText(this.selectedFile, "UTF-8");
fileReader.onload = () => {
console.log(JSON.parse(fileReader.result));
}
fileReader.onerror = (error) => {
console.log(error);
}
}

Remove __MACOSX/ files from zip archive using javascript and fflate

I'm testing fflate to replace JSZip that sometimes will fail to open archives created using macOS or windows built-in compression utility. The library works fine and I'm able to create and read zip files content. I've done a test with an archive created using macOS and I've noticed that inside the achive the compression utility will create some __MACOSX/_.filename.ext files for each entry of the archive. I want to remove these files from the file list when the user open the zip using my app but I don't know how to proceed. Is there any solution I can use with vue and javascript to achive this?
Here is the code I'm using in my vue methods to read zip files
async handleFiles(e) {
const file = await this.readFile(e.dataTransfer.files[0]);
const unzip = unzipSync(file);
Object.keys(unzip).forEach( (key) => {
this.files.push({name: key, data: unzip[key]});
});
},
readFile(file) {
return new Promise( (resolve,reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onerror = reject;
reader.onloadend = () => {
resolve(new Uint8Array(reader.result));
}
});
}
Have you considered using Array.filter?
Object.keys(unzip)
.filter(key => {
return !key.match(/^__MACOSX\//);
})
.forEach( (key) => {
this.files.push({name: key, data: unzip[key]});
});

Reactjs Input Upload doesn't return local URL

I have a problem when trying to display image preview before upload it to server. I 'm using reactjs.
My problem is when I try to upload an image I got the file data but when I'm using reader, it doesn't return local URL and just show undefined
this is the topic that I tried to follow get-image-preview-before-uploading-in-react
but when I try to check my image local url it return undefined
this is what I import in my file:
import React, {Component} from "react";
import { MDBContainer, MDBRow, MDBCol, MDBBtn, MDBIcon, MDBInput, MDBDropdown, MDBDropdownToggle, MDBDropdownMenu, MDBDropdownItem } from 'mdbreact';
this is my js:
<p className="text-upload">Front Desain</p>
<input ref="file" type="file" name="front Design" onChange={this.frontDesign}/>
this is my method or function:
frontDesign = (e) =>{
var file = this.refs.file.files[0];
var reader = new FileReader();
var url = reader.readAsDataURL(file);
reader.onloadend = function (e) {
this.setState({
form:{
frontDesign: [reader.result]
}
})
}.bind(this);
console.log("Check Data : ", file)
console.log("Check URL : ", url)
}
and this is my state:
state ={
form:{
frontDesign: [],
}
}
this is my console:
This my codesandbox:
https://codesandbox.io/s/tender-mclaren-zb1l7?fontsize=14
can someone help me to solve this?
From the mozilla website it seams you need to add a load event listener to your reader. This sample code is not supported in some versions of IE.
...
reader.addEventListener("load", () => {
this.setState(state => ({
...state,
form:{
frontDesign: [reader.result]
}
}))
const url = reader.result;
console.log(url);
}, false);
...
Working condeSanbox here: https://codesandbox.io/s/affectionate-lamport-dnbij
Do not need use ref here. Try to code below
frontDesign = (e) => {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = (e) => {
//Image URL e.target.result
this.setState({
form:{
frontDesign: [e.target.result]
}
})
}
reader.readAsDataURL(file);
}

Write file to disk from blob in electron application

I am creating an Electron Application in which I am recording data from webcam and desktop, at the end of the recording session, I want to save the data to a file in the background. I do not know how to write the data from a blob to a file directly. Any suggestions?
Below is my current handling for MediaRecord Stop event.
this.mediaRecorder.onstop = (e) => {
var blob = new Blob(this.chunks,
{ 'type' : 'video/mp4; codecs=H.264' });
var fs = require('fs');
var fr = new FileReader();
var data = null;
fr.onload = () => {
data = fr.result;
fs.writeFile("test.mp4", data, err => {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
};
fr.readAsArrayBuffer(blob);
}
You can do it using FileReader and Buffer.
In the renderer process, send the event to the main process to save the file with the buffer:
function saveBlob(blob) {
let reader = new FileReader()
reader.onload = function() {
if (reader.readyState == 2) {
var buffer = new Buffer(reader.result)
ipcRenderer.send(SAVE_FILE, fileName, buffer)
console.log(`Saving ${JSON.stringify({ fileName, size: blob.size })}`)
}
}
reader.readAsArrayBuffer(blob)
}
Get back the confirmation:
ipcRenderer.on(SAVED_FILE, (event, path) => {
console.log("Saved file " + path)
})
(SAVE_FILE and SAVED_FILE are static strings containing event name)
and in the main process:
ipcMain.on(SAVE_FILE, (event, path, buffer) => {
outputFile(path, buffer, err => {
if (err) {
event.sender.send(ERROR, err.message)
} else {
event.sender.send(SAVED_FILE, path)
}
})
})
outputFile is from 'fs-extra'
Handling node operations in main process is preferred. See Electron Security suggestions.
If you do want to not use main process, you can use 'electron-remote' to create background processes to write the file. Additionally, you can invoke ffmpeg in the background process to compress/encode the file into different format.

PSD.js in react error fs.readFileSync is not a function

I have a reactjs project using psd.js and on my dropzone config like this
accept: function(file, done){
const reader = new FileReader();
reader.onload = handleReaderLoad;
reader.readAsDataURL(file);
function handleReaderLoad(evt) {
console.log(evt.target.result);
let psdFile = PSD.fromFile(evt.target.result);
psdFile.parse();
console.log(psdFile);
}
done();
},
The error is:
Uncaught TypeError: fs.readFileSync is not a function
at Function.fromFile (init.coffee:6)
at FileReader.handleReaderLoad (index.js?03a7:153)
in my webpack config i inlclude :
node: {
fs: 'empty'
},
Because if I don't include it, the error is: not found fs module
Please help.
You should use PSD.fromEvent(evt), not PSD.fromFile.
The former reads the blob from a file input, while the latter tries to hit the filesystem which is obviously absent in the browser context.
So I guess your code should look like this (but I'm not quite sure)
accept: function(file, done){
const reader = new FileReader();
reader.onload = handleReaderLoad;
reader.readAsDataURL(file);
function handleReaderLoad(evt) {
PSD.fromEvent(evt).then(function (psd) {
// here you can access the parsed file as psd
console.log(psd.tree().export());
done();
});
}
},

Categories