I'm trying to upload file, then convert it to base64 string and add to object. but it seems did'nt work.
console.log() every time show empty object
<input type="file" (change)="onChange($event)" accept="image/jpeg, image/png" />
<input type="submit" value="send" (click)="upload()" />
functions:
onChange(fileInput: any) {
let image: any = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.onload = () => {
reader.readAsDataURL(image);
let photo: AddPhoto = new AddPhoto();
photo.base64Image = reader.result;
this.product.photos = [];
this.product.photos.push(photo);
};
}
upload() {
console.log(this.product);
}
One thing here is that, reader.onload will be called only when the file is successfully loaded by reader.readAsDataURL(). Here logically it should not be written inside reader.onload. Take readAsDataURL outside the onload function so that it remains inside onChange function. Then it should work. You code should look something as follows.
onChange(fileInput: any) {
let image: any = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.onload = () => {
let photo: AddPhoto = new AddPhoto();
photo.base64Image = reader.result;
this.product.photos = [];
this.product.photos.push(photo);
};
reader.readAsDataURL(image);
}
This works well for me...hope it helps
uploadFileImage(fileInput: any)
{
var files = fileInput.target.files;
var file = files[0];
if (files && file)
{
var reader = new FileReader();
reader.onload = function(readerEvt: any)
{
var binaryString = readerEvt.target.result;
var base64 = btoa(binaryString);
this.product.photos = [];
this.product.photos.push(base64);
};
reader.readAsBinaryString(file);
}
}
Related
So I am trying to convert a file from tag. This is how my javascript code looks like:
var file = document.getElementById("file").files[0];
if (file) {
var filereader = new FileReader();
filereader.readAsDataURL(file);
filereader.onload = function (evt) {
var base64 = evt.target.result;
}
}
That returns undefined.
two little helper and an example.
const blobToDataUrl = blob => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
const blobToBase64 = blob => blobToDataUrl(blob).then(text => text.slice(text.indexOf(",")));
for(let file of document.getElementById("file").files) {
blobToBase64(file).then(base64 => console.log(file, base64));
}
But why the Promises?
Because your next question will be: How do I get the base64 string out of onload? and the short answer is You don't. A longer answer would be: It's like asking how to get something from the future into the now. You can't.
Promises are placeholder/wrapper for values that will eventually be available; but not yet. And they are the foundation of async functions.
So let's skip messing with callbacks and get right to the point where you write
for(let file of document.getElementById("file").files) {
const base64 = await blobToBase64(file);
console.log(file, base64);
}
but for that you will have to brush up on async and await.
I think you have missed the return statement in the code.
Replace your function with the following lines:
var file = document.getElementById("file").files[0];
if (file) {
var filereader = new FileReader();
filereader.readAsDataURL(file);
filereader.onload = function (evt) {
var base64 = evt.target.result;
return base64
}
}
i am trying to use filereader to access a blob file located locally, such as c drive, then converts it back to object URL as img src. it is not working, can anyone help this?
never found anyone try to access a blob file from disk. what is the blob file type extension?
const imageOut = document.querySelector('#image-out');
imageOut.addEventListener('load', () => {
const reader = new FileReader();
reader.addEventListener('load', () => {
var f = File.createFromFileName("file:///C:/blob.blb");
const arrayBuffer = reader.readAsArrayBuffer(f);
const blob = new Blob([arrayBuffer], { type: mimeType });
imageOut.src = URL.createObjectURL(blob);
});
});
empty, not show
Check how to use blob here it is clearly explained and it should be enough to get you going.
Try this:
Assuming that file:///C:/blob.blb exists and you are sure, then do it like so:
imageOut.addEventListener('load', () => {
const reader = new FileReader();
var f = File.createFromFileName("file:///C:/blob.blb");
reader.addEventListener('load', (e) => {
const arrayBuffer = reader.readAsArrayBuffer(f);
global.blob = new Blob([arrayBuffer], { type: f.type});
});
// notice this is outside the reader Load.
var intval = setInterval(function(){
if(blob !== undefined){
imageOut.src = URL.createObjectURL(blob);
clearInterval(intval);
}
}, 100);
});
I hope it helps.
I've got a form for uploading Avatar image and I have to send the image file in the format of binary string; so far I've tried ReadAsBinaryString from FileReader but it's not working:(
here's my code:
<form onSubmit={this.onFormSubmit}>
<div className="row justify-content-center mb-2">
<input type="file" id="avatar" accept="image/png, image/jpeg"
onChange={this.uploadedImage} />
<button type="submit" className="btn btn-sm btn-info">Send</button>
</div>
</form>
and that is how I'm trying to use ReadAsBinaryString in uploadedImage function:
uploadedImage(e) {
let reader = new FileReader();
let file = e.target.files[0];
console.log(file); //I can see the file's info
reader.onload= () => {
var array = new Uint32Array(file);
console.log("_+_array:",array); // the array is empty!
var binaryString = String.fromCharCode.apply(null,array) ;
console.log("__binaryString:",binaryString);
this.setState({
file: binaryString
},()=>{
console.log(this.state.file);//ergo file is set to an empty image
});
}
reader.readAsArrayBuffer(file)
}
so to sum it up, I get a file but I can't convert it to byte array; Is there anything wrong with this code or this approach is completely wrong?
This approach worked for me:
function readFileDataAsBase64(e) {
const file = e.target.files[0];
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(event.target.result);
};
reader.onerror = (err) => {
reject(err);
};
reader.readAsDataURL(file);
});
}
You can call reader.readAsBinaryString() if you wish to use binary string. More here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
You are trying to read the file data using the file variable which contains the file info not the file contents. Try sth like the following:
FileReader documentation
uploadedImage(e) {
let reader = new FileReader();
let file = e.target.files[0];
console.log(file); //I can see the file's info
reader.onload= () => {
var array = new Uint32Array(reader.result); // read the actual file contents
console.log("_+_array:",array); // the array is empty!
var binaryString = String.fromCharCode.apply(null,array) ;
console.log("__binaryString:",binaryString);
this.setState({
file: binaryString
},()=>{
console.log(this.state.file);//ergo file is set to an empty image
});
}
reader.readAsArrayBuffer(file)
}
Just to add to tomericco's answer, here is one with few more lines to get the actual final byte array :
const test_function = async () => {
... ... ...
const get_file_array = (file) => {
return new Promise((acc, err) => {
const reader = new FileReader();
reader.onload = (event) => { acc(event.target.result) };
reader.onerror = (err) => { err(err) };
reader.readAsArrayBuffer(file);
});
}
const temp = await get_file_array(files[0])
console.log('here we finally ve the file as a ArrayBuffer : ',temp);
const fileb = new Uint8Array(fileb)
... ... ...
}
where file is directly the File object u want to read , this has to be done in a async function...
const file = e.target.files[0];
// we need to get the raw bytes
const buffer = await file.arrayBuffer();
// each entry of array should contain 8 bits
const bytes = new Uint8Array(buffer);
Converting an image to base64 in angular 2, image is uploaded from local . Current am using fileLoadedEvent.target.result. The problem is, when I send this base64 string through REST services to java, it is not able to decode it. When i try this base64 string with free online encoder-decoder, there also I cannot see decoded image. I tried using canvas also. Am not getting proper result. One thing is sure the base64 string what am getting is not proper one, do I need to add any package for this ? Or in angular 2 is there any perticular way to encode the image to base64 as it was there in angular 1 - angular-base64-upload package.
Pls find below my sample code
onFileChangeEncodeImageFileAsURL(event:any,imgLogoUpload:any,imageForLogo:any,imageDiv:any)
{
var filesSelected = imgLogoUpload.files;
var self = this;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
//Reading Image file, encode and display
var reader: FileReader = new FileReader();
reader.onloadend = function(fileLoadedEvent:any) {
//SECOND METHO
var imgSrcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = imageForLogo;
newImage.src = imgSrcData;
imageDiv.innerHTML = newImage.outerHTML;
}
reader.readAsDataURL(fileToLoad);
}
}
Working plunkr for base64 String
https://plnkr.co/edit/PFfebmnqH0eQR9I92v0G?p=preview
handleFileSelect(evt){
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload =this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.base64textString= btoa(binaryString);
console.log(btoa(binaryString));
}
I modified Parth Ghiya answer a bit, so you can upload 1- many images, and they are all stored in an array as base64 encoded strings
base64textString = [];
onUploadChange(evt: any) {
const file = evt.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = this.handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
handleReaderLoaded(e) {
this.base64textString.push('data:image/png;base64,' + btoa(e.target.result));
}
HTML file
<input type="file" (change)="onUploadChange($event)" accept=".png, .jpg, .jpeg, .pdf" />
<img *ngFor="let item of base64textString" src={{item}} alt="" id="img">
another solution thats works for base64 is something like this post
https://stackoverflow.com/a/36281449/6420568
in my case, i did
getImagem(readerEvt, midia){
//console.log('change no input file', readerEvt);
let file = readerEvt.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//console.log('base64 do arquivo',reader.result);
midia.binario = btoa(reader.result);
//console.log('base64 do arquivo codificado',midia.binario);
};
reader.onerror = function (error) {
console.log('Erro ao ler a imagem : ', error);
};
}
and html component
<input type="file" class="form-control" (change)="getImagem($event, imagem)">
<img class="img-responsive" src="{{imagem.binario | decode64 }}" alt="imagem..." style="width: 200px;"/>
to display the image, i created the pipe decode64
#Pipe({
name: 'decode64'
})
export class Decode64Pipe implements PipeTransform {
transform(value: any, args?: any): any {
let a = '';
if(value){
a = atob(value);
}
return a;
}
}
Have you tried using btoa or Crypto.js to encode the image to base64 ?
link to cryptojs - https://code.google.com/archive/p/crypto-js/
var imgSrcData = window.btoa(fileLoadedEvent.target.result);
or
var imgSrcData = CryptoJS.enc.Base64.stringify(fileLoadedEvent.target.result);
Here is the same code from Parth Ghiya but written in ES6/TypeScript format
picture: string;
handleFileSelect(evt){
const file = evt.target.files[0];
if (!file) {
return false;
}
const reader = new FileReader();
reader.onload = () => {
this.picture = reader.result as string;
};
console.log(btoa(this.picture));
}
I have a come up with an answer with calling the HTTP request for post method with a json
1.event param is coming from the HTML input tag.
2. self.imagesrc is a component variable to store the data and to use that in the header file we need to cast the "this" to a self variable and use it in the reader. Onload function
3. this.server is the API calling service component variable I used in this component
UploadImages(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
var self = this;
reader.onload = function() {
self.imageSrc = reader.result.toString();
};
var image_data = {
authentication_token: this.UD.getAuth_key ,
fileToUpload: this.imageSrc,
attachable_type: "Photo"
};
this.server.photo_Upload(image_data).subscribe(response => {
if (response["success"]) {
console.log(response);
} else {
console.log(response);
}
});
}
Please consider using this package: image-to-base64
Generate a image to base64, you can make this using a path or url.
Or this accepted answer
I have a list of files I need to save and in addition to the name I need to send the readAsDataURL to the server as well.
The problem is I am not sure how to do it with the async nature of readAsDataURL. Because to save the DATAURL to the array I need to look up the name of the file which is in the files list. and I cannot pass the file to the async method of readAsDataURL. How do you write this properly to work? The end result is I want a list of files sent to the server in one JSZip file.
function saveFileList(files)
{
for (var i = 0, file; file = files[i]; i++) {
var fr = new FileReader();
fr.onload = function(e){
if (e.target.readyState == FileReader.DONE) {
var tt = e.target.result.split(",")[1];
//update the record in the list with the result
}
};
var pp = fr.readAsDataURL(file);
}
If you have FileList and you need to get array of base64 string, you need do this
export async function fileListToBase64(fileList) {
// create function which return resolved promise
// with data:base64 string
function getBase64(file) {
const reader = new FileReader()
return new Promise(resolve => {
reader.onload = ev => {
resolve(ev.target.result)
}
reader.readAsDataURL(file)
})
}
// here will be array of promisified functions
const promises = []
// loop through fileList with for loop
for (let i = 0; i < fileList.length; i++) {
promises.push(getBase64(fileList[i]))
}
// array with base64 strings
return await Promise.all(promises)
}
use it like this
const arrayOfBase64 = await fileListToBase64(yourFileList)
You need another function around it, so you can pass the file in. Try this:
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
if(reader.readyState == FileReader.DONE)
alert(theFile.name); // The file that was passed in.
}
};
})(file);
reader.readAsDataURL(file);
An alternative to Russell G's answer:
var reader = new FileReader();
reader.onload = function(event){
payload = event.target.result;
var filename = file.name, filetype = file.type;//etc
//trigger a custom event or execute a callback here to send your data to server.
};
reader.onerror = function(event){
//handle any error in here.
};
reader.readAsDataURL(file);