Cannot upload image in vue.js laravel - javascript

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.

Related

How would I convert an image to base64 in reactJS

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)

TinyMCE 4.3 only uploading one image

TinyMCE is not allowing multiple file uploads in a post. You can select a file, and it will insert into the TinyMCE editor however once you submit, only the last inserted image is uploaded.
Below is the code I am working with: (the [0] is removed on the second attempt in which I was thinking TinyMCE would handle the files array)
if (meta.filetype == 'image') {
$('#upload').trigger('click')
$('#upload').on('change', function() {
var file = this.files[0]
var reader = new FileReader()
var name = file.name.split('.')[0]
var blobCache = tinymce.activeEditor.editorUpload.blobCache
var blobInfo = blobCache.create(name, file, reader.result)
blobCache.add(blobInfo);
reader.onload = function(e) {
callback(blobInfo.blobUri(), {
alt: file.name,
title: name
})
}
reader.readAsDataURL(file)
})
}
}
I have tried to append additional files with a for loop and removed the [0] from files and split without success.
file_picker_callback: function(callback, value, meta) {
if (meta.filetype == 'image') {
$('#upload').trigger('click')
$('#upload').on('change', function() {
var file = this.files//[0]
var reader = new FileReader()
var name = []
for(var x = 0; x < file.length; x++) {
name.push(file[x].name.split('.'))
}
var blobCache = tinymce.activeEditor.editorUpload.blobCache
var blobInfo = blobCache.create(name, file, reader.result)
blobCache.add(blobInfo);
reader.onload = function(e) {
callback(blobInfo.blobUri(), {alt: file.name, title: name})
}
reader.readAsDataURL(file)
})
}
}
I have also tried allowing auto upload which only work for the first image and the rest fallback to base64 in the database. Lastly, I tried to combine all files in order to upload however I'm not seeing different file names in console.log. For instance I attach one file, I see one file in console.log, I attach another, I see two responses in console.log but with the most recent attached file but only the last attached image will upload on submit. It seems that TinyMCE overwrites the file with each image attachemnt.
Is there a different approach to this so I can add images to a post with TinyMCE and upon submit, they are all uploaded instead of the last image attached?
Changed to the following now for a working solution. Using the name for the first argument when calling blobCache.create was the cause of the issue, a unique blobid is required instead.
file_picker_callback: function(callback, value, meta) {
if (meta.filetype == 'image') {
$('#upload').on('change', function() {
var file = this.files[0]
var reader = new FileReader()
reader.onload = function(e) {
// var name = file.name.split('.')[0] // replaced with id below
// var base64 = reader.result.split(',')[1]; // for base64
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache
var blobInfo = blobCache.create(id, file, reader.result)
blobCache.add(blobInfo);
callback(blobInfo.blobUri(), {alt: file.name, title: name})
}
reader.readAsDataURL(file)
})
$('#upload').trigger('click')
}
}

Converting an image to base64 in angular 2

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

Can't return value of fileReader result in AngularJS service

I'm trying to write a service which reads the image file from an HTML input element. I want this service to return the HTML img object with the updated attribute from the read image file (the base64 string). My service is now this:
.service('ReadLocalImageService', [function () {
this.openLocalImage = function (file) {
var img = document.createElement("img");
var fileReader = new FileReader();
fileReader.onload = function (e) {
img.src = e.target.result;
};
fileReader.readAsDataURL(file);
return img.src;
};
}]);
The img.src in this case is returned empty, like this:
If I put a console.log(img.src) inside the fileReader.onload, it prints out what I want. It seems like the function openLocalImage is returning the img.src before e.target.result is assigned to it.
I couldn't manage to work this around nor find the correct topic about this problem. Could anyone help me solve this or explain me why it doesn't work?
Its because img was not loaded yet. Here is a solution
.service('ReadLocalImageService', [function () {
this.openLocalImage = function (file, callback) {
var img = document.createElement("img");
var fileReader = new FileReader();
fileReader.onload = function (e) {
img.src = e.target.result;
callback(img.src);
};
fileReader.readAsDataURL(file);
};
}]);
We will pass a callback function and receive img.src as its param. To use it
ReadLocalImageService.openLocalImage(myImage, function(imgSrc) {
// use imgSrc
});

Get base64 of audio data from Cordova Capture

I am using ngCordova Capture to write this code by recording audio and send the base64 somewhere (via REST). I could get the Capture Audio to work but once it returns the audioURI, I cannot get the data from the filesystem as base64. My code is below:
$cordovaCapture.captureAudio(options).then(function(audioURI) {
$scope.post.tracId = $scope.tracId;
$scope.post.type = 'audio';
console.log('audioURI:');
console.log(audioURI);
var path = audioURI[0].localURL;
console.log('path:');
console.log(path);
window.resolveLocalFileSystemURL(path, function(fileObj) {
var reader = new FileReader();
console.log('fileObj:');
console.log(fileObj);
reader.onloadend = function (event) {
console.log('reader.result:');
console.log(reader.result);
console.log('event.result:');
console.log(event.result);
}
reader.onload = function(event2) {
console.log('event2.result:');
console.log(event2.target.result);
};
reader.readAsDataURL(fileObj);
console.log(fileObj.filesystem.root.nativeURL + ' ' + fileObj.name);
$cordovaFile.readAsDataURL(fileObj.filesystem.root.nativeURL, fileObj.name)
.then(function (success) {
console.log('success:');
console.log(success);
}, function (error) {
// error
});
});
Here is the output in console log:
So how do I get the base64 data from the .wav file?
I have been reading these links:
PhoneGap FileReader/readAsDataURL Not Triggering Callbacks
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
http://jsfiddle.net/eliseosoto/JHQnk/
http://community.phonegap.com/nitobi/topics/filereader_onload_not_working_with_phonegap_build_2_5_0
Had same problem, which I fixed using both the Cordova Capture and Cordova File plugin.
navigator.device.capture.captureAudio(function (audioFiles) {
var audioFile = audioFiles[0],
fileReader = new FileReader(),
file;
fileReader.onload = function (readerEvt) {
var base64 = readerEvt.target.result;
};
//fileReader.reasAsDataURL(audioFile); //This will result in your problem.
file = new window.File(audioFile.name, audioFile.localURL,
audioFile.type, audioFile.lastModifiedDate, audioFile.size);
fileReader.readAsDataURL(file); //This will result in the solution.
});

Categories

Resources