Encode MP3 file to base64 string in Ionic - angularjs

I'm working on a app that use cordova-plugin-media to record and audio file, and now I want to encode this file to base64 string, for now I can locate the file but when I try to encode it I get this :
"{"$$state":{"status":0}}"
Here is my code
audio.stopRecord();
audio.play();
if(device.platform == "iOS")
{
var path = cordova.file.tempDirectory;
}
else if(device.platform == "Android")
{
var path = cordova.file.externalRootDirectory;
}
var filename = name + extension;
var filepath = path + filename;
console.log(filepath);
console.log(JSON.stringify($cordovaFile.readAsDataURL(path, filename)));
file path : file:///storage/emulated/0/tPUhcxUKhmLUrWK3Qkqhc69OxeEIWyYrhEB0he9OwM0ffmjY2OUh3TLbFTsApdpIpjxyuC2wouyCs6m7uvdOCHCMiw9mbLMGYM25.mp3
Can any one help me with this??
Thanks

readAsDataURL needs a file object, it won't work with a string path.
Give the following code a try, working on iOS and Android
window.resolveLocalFileSystemURL(path, function(fileEntry) {fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var base64String = evt.target.result;
};
reader.readAsDataURL(file);
});}, function(e){console.log("error:" + JSON.stringify(e));});

Related

converting image source into file and append the file in rest api

I have an image source , i need to convert it into png file and append it to backend and send. upload is successfull ,but when we retrieve the stored file from backend , it has invalid file format error. I think it was not converted to base64 and because of this we have this issue. I am using $base64 dependency to covert my source.
source = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQVR4Xjy9Z6xlaXYdts6999ycc3o5p6pXVV3V1Xl6unt62CI5nCFFw6RoyIZtSDIMWTb8wyBk2DBgyYZ/CIT+SJRJGDJNWrboiRRnunu6OR0qp5fq5XRzzjkcY+03ozcoVNebV/eee8639157rbV3Kf/kj35XazbbsFrtqJSa2Ns9Qj5XQa8LOOw+mE0O1Kt9WCxOVCtN5HMlmMx=="
$scope.uploadFile = function(source){
var imageBase64 = $base64.encode(source);
var blob = new Blob([imageBase64], {
type: 'image/png'
});
var filename = Math.random().toString(36).substring(7);
var file = new File([blob], filename + '.png',{type:'image/png'});
$scope.file = file;
var json = {
"json": {
"request":{
"servicetype":"4",
"functiontype": "4012",
"session":{
"sessionid":session
}
}
}
};
fileUpload.uploadFileToEmp( json, file ).then(function(res){
}
}
});
}

How can i generate a blob url?

I have a function that will determine if the gif is animated or non-animated. Everything is working fine, until i upload those gif to the server, and load it, the blob url is a empty string. How can i generate a blob url for this?
Due to the blob url being empty string, i get parameter 1 is not of type 'blob'
The function below determines if the gif is animated or not.
$scope.isNotAnimatedGIF = function(file) {
var reader = new FileReader();
return new Promise(function(resolve, reject) {
reader.onload = function (e) {
var gifInfo = gify.getInfo(reader.result);
if (gifInfo.images.length <= 1) {
file.animatedGIF = false;
resolve(true);
} else {
file.animatedGIF = true;
resolve(false);
}
}
reader.readAsArrayBuffer(file);
});
}
I am using Angular 1.4.10
Thank you !
You can use URL.createObjectURL() to create Blob url.
The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
DEMO
function createbloburl(file, type) {
var blob = new Blob([file], {
type: type || 'application/*'
});
file = window.URL.createObjectURL(blob);
return file;
}
document.querySelector('#file').addEventListener('change', function(e) {
var file = e.currentTarget.files[0];
if (file) {
file = createbloburl(file, file.type);
document.querySelector('iframe').src = file;
//console.log(file)
}
})
<input id="file" type="file">
<iframe src=""></iframe>
try this reader.readAsDataURL(Blob|File).
you can find more from here

Encode PDF to base64 in ReactJS

Please help me!
How can I encode file to string base64 in react
handleUploadFile(event) {
let file = event.target.files[0]
// here encoding file base64?
this.setState({
fileData: file,
fileName: file.name
})
}
Here is what you can try out :
handleUploadFile(event) {
let selectedFile = event.target.files;
let file = null;
let fileName = "";
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
let fileToLoad = selectedFile[0];
fileName = fileToLoad.name;
// FileReader function for read the file.
let fileReader = new FileReader();
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
file = fileLoadedEvent.target.result;
// Print data in console
console.log(file);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
this.setState({
fileData: file,
fileName: fileName
})
}
You may need to change it for multiple files though.

convert file path to actual bytes?

I have the following path
"file:///var/mobile/Containers/Data/Application/92C91B4A-B7F9-40F8-B8AD-646DA0607942/Library/NoCloud/Z7sY4cdv_photo_001.jpg"
how can I convert this file path to the actual binary representation of the file? I've tried using the file reader in every way imaginable but keep on getting error codes. THANKS
so my expect result is to have the bytes into a javaScript object, basically assign a image to a object.
try that :
$scope.getFileBinary = function(fileUri){
var xhr = new XMLHttpRequest();
xhr.open("GET", fileUri, true);
//xhr.responseType = 'blob';
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
if (this.status == 200 || this.status === 0) {
// Note: .response instead of .responseText
var blob = new Blob([this.response], {
type: 'image/png'
});
var reader = new FileReader();
reader.onload = function() {
// this gets read of the mime-type data header
var actual_contents = reader.result.slice(reader.result.indexOf(',') + 1);
d.resolve(actual_contents );
};
reader.readAsDataURL(blob);
}
};
xhr.send();
}

Titanium save files from stream

I have a streamer from server(SOAP) with different type of files, and i what seve it in physical storage.
I try this code but i only create file with my string.
api.getFile(function(fileString) {
var original = 'Appcelerator';
var decoded = Ti.Utils.base64decode(fileString);
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, 'Settings');
var newFile = Titanium.Filesystem.getFile(Settings.nativePath, 'Settings.pdf');
newFile.createFile(decoded);
// Ti.API.info('newfile: '+newFile.read());
});
}
}
try this one..
var original = 'Appcelerator';
var decoded = Ti.Utils.base64decode(fileString);
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, 'Settings');
Settings.createDirectory();
var newFile = Titanium.Filesystem.getFile(Settings.nativePath, 'Settings.pdf');
newFile.write(decoded);

Resources