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
Related
I have this function where I call a function and have a local file as the parameter to convert it to base64.
export const fileToBase64 = (filename, filepath) => {
return new Promise(resolve => {
var file = new File([filename], filepath);
var reader = new FileReader();
// Read file content on file loaded event
reader.onload = function(event) {
resolve(event.target.result);
};
// Convert data to base64
reader.readAsDataURL(file);
});
}
Importing the function
fileToBase64("shield.png", "./form").then(result => {
console.log(result);
console.log("here");
});
gives me an output as
data:application/octet-stream;base64,c2hpZWxkLnBuZw==
here
I want base64 information, but noticing the file the application/octet-stream is wrong? I entered an image so shouldn't it be
data:image/pgn;base64,c2hpZWxkLnBuZw==
https://medium.com/#simmibadhan/converting-file-to-base64-on-javascript-client-side-b2dfdfed75f6
try this I think this should helpfull
let buff = new Buffer(result, 'base64');
let text = buff.toString('ascii');
console.log(text)
I'm trying to upload an image which is in base64 format using below code
upload: function(e) {
const tmpFiles = e.target.files;
if (tmpFiles.length === 0) {
return false;
}
const file = tmpFiles[0];
const self = this;
const reader = new FileReader();
reader.onload = function(e) {
self.form.imageData.push(e.target.result);
}
}
issue is if i access this.form.imageData outside onload function then i get null and in my controller also i'm not getting image data, but when i print it using self.form.imageData inside onload function then i get image data in base64 encoded format.
Any help is highly appreciated.
I am trying to get a blob response from a request, and then generate a URL from that blob and set this URL as an image's source.
But the image is not loading.
This is my HTML:
<img src="{{previewSignsrc}}" alt="Sign Thumbnail">
And this is my .ts file:
this.signModalDataService.getPreviewSignature({'name': this.SignatureName, 'font_type': 0});
this.signModalDataService.previewSignature
.subscribe((res) => {
console.log(res);
let blob = new Blob([res['_body']], {type: 'image/png'});
this.previewSignsrc = URL.createObjectURL(blob);
this.showPreviewSign = true;
});
I used same method to set url for ng2-pdfviewer and it worked fine.
You can dislay image like this code
this.config.getData()
.subscribe((blob : any) => {
let objectURL = URL.createObjectURL(blob);
this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);
});
If your data is base64 display like this
this.config.getData()
.subscribe((baseImage : any) => {
let objectURL = 'data:image/jpeg;base64,' + baseImage.image;
this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL);
});
Demo https://stackblitz.com/edit/display-image-from-api
As was metioned earlier by Memo 313 MediaSA, FileReader works.
const reader = new FileReader();
reader.readAsDataURL(data); //FileStream response from .NET core backend
reader.onload = _event => {
url = reader.result; //url declared earlier
image.nativeElement.src = url; //image declared earlier
};
You can use new FileReader(); I tried so much codes and that's the only one that worked for me.
var reader = new FileReader ();
reader.readAsDataURL(response) <= from inner . subscribe
reader.onload = (_event) => {
this.retrieveURL = reader.result;
}
.html
[src]="retrieve URL"
Bear with me I typed from my cellphone
That's all no need to use sanitizers, hope it helps somebody out there, ooh I am using Angular8
this code is the best for blob(for example asp file stream in backend) and 100% work.
.ts:
image: any;
constructor(
private sanitizer: DomSanitizer,
) { }
this.signModalDataService.previewSignature
.subscribe(blob => {
let objectURL = URL.createObjectURL(blob);
this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);
})
.html
<img [src]="image">
If you use JsonConvert from a .Net API to return an object in which one of the fields is the image byte[] it will convert it to a base64 string. Then you don't need anything special when calling the api or displaying the image.
This works for me:
this.httpClient.get(Endpoints.PRODUCTS + '/pictures/download', {'params': queryParams, responseType: 'blob'})
.subscribe(
value => {
// Add Preview
const reader = new FileReader();
reader.readAsBinaryString(value);
const addPreview = (fileBase64) => {
this.urls.push(`data:${value.type};base64,${btoa(fileBase64)}`);
};
reader.onload = function (e) {
addPreview(e.target.result);
};
},
(error) => {
// Refactor
// this.errorList = error.error.data.errorList;
console.log(error);
})
;
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);
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);
}
}