Cannot convert to System.Byte - javascript

I am using trying to send an ajax post request with some text & files. However the accepted file format is base64binary (it is specified by the api to accept the post request)
Am using the below javascript function to convert the image file to a base64:
function encodeImageFileAsURL(){
var filesSelected = document.getElementById("image").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
convertedimage = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
//alert("Converted Base64 version is "+document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is "+document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
And using a simple ajax call to send the data.
This is the response I am getting from the api:
Cannot convert data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABmJLR0QA/wD/AP+gvaeTAAAZDElEQVR4nO3deXhV5Z0H8O/vnJsElE1LRRYd0FqXoK3FEbKo6YxLccFWvZCAC0uWoi3aqe10pu0Y22qn1qVVUUkIWgWSEO1Y6IiK9sGaBbRoRVDbqYoiqBVUQCDLPec3f4AtUsDce5b33Hu+n+fxDx9z3vcr5Hzve5Z7DkBERERERERERERERERERERERERERERERERERERERBElpgOQ/wqTi/IH5m0dCsc9TIDBKtZgAQYrdDCAwbt+SkREB+29rSpcAFt2/6sjwCYFNilkk6hssoB3exLu5pXHbNiI2lo3tP8pCgQLIEsVJW/ta+f1P8FxUCiCo0QwSoGRUIwCMByAFXCEbgBvimCdqrwu0HUAXrUc+0X7vTf/vHx5bSrg+ckHLIAscOrlv/qM3dVVBJGTLcGJCpwExecA2Kaz7UcXgJcAXSMqL4rg2YPyCp59/IHLt5sORp/EAoigooo5x0HtYoFbAkgRgOOQ/X9XKQB/BNAuQLvrpFo7WmZuMB0q7rL9lyonlJQ3DFO454vgTFV8GX87Ts9tCrwuwDJVecJN9Hls5YJLt5rOFDcsAEPGld890tZEUi2cD0UxgITpTCYpsF2gy0Wsh3vy8v7nmfuv2Gw6UxywAEJUkmw4Vm23QkWTonKC6TwR5grQ4aq2pNy85mdbpr1jOlCuYgEEbMwFcw7q089OqqIS0BLwzzxd3QCWAlI/3BnwaEvLRMd0oFzCX8aAjJtYd6ZtS7UqLgDQx3SeHPEugGYRrWtrrF5rOkwuYAH4aEz1nLz8bdYlULlaoGNN58lhDoClCvlFR1Plk6bDZDMWgA/KKuYM7lbrGwBmAjjMdJ6Y+Yuq3tm9Q+tXLanZYTpMtmEBeFCUvHu4JPK+A+h0KPqbzhNzGwG9Pd/pmb285aqPTIfJFiyADJyerB+VsvV... to System.Byte.
Parameter name: type ---> Input string was not in a correct format.
Would anyone tell me about the way or approach to fix this?
Thank you in advance.

Related

XMLHttpRequest how send long base64 string as parameter?

i am trying to upload some images to a API but the API only accepts the fallowing format to upload the image, base64 string:
curl --location --request POST
"https://api.site.com/send?expiration=600&key=APIKEY"
--form "image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
i can send successfully a small image like that:
var req = new XMLHttpRequest();
req.open('POST', 'https://api.site.com/send', true);
var params='key=999999999&image=';
var params2 = 'iVBORw0KGgoAAAANSUhEUgAAABQAAAAVCAYAAABG1c6oAAADEElEQVQ4T21VOUgzURD+1nhERSwsLEQwhZ0H2CkeaCobKwvBG8VKbLWy0VZEwUKLeJJAGiuPwkSwSiEqYmORoGChICheeO+/34R5/0twYNndtzPf++abmbeO6xmy7Pf3F47jyMXnq6sr3NzcyHtxcTEaGhokgqFcs81RwO/vb+Tk5MhFW11dxc7ODvb39/H+/i6B9MnNzZV7S0sLxsbG0NfX9zeg7nh4eIiRkRFhRSsoKMDHx4c8KxjvZPfz84PKykpsbW2hubk5zVgZ8mMkEkF/f78J9Pl8EqSmgPpO1vQh48XFRYyPj/8HXF9fx9DQkDgQhKlzR9VJ9SSY+nDNLgExnM/PT/fu7g51dXV4eHgQIC2KgtlBCmKztYEl5YGBAWxubppUNSUyofiDg4MIBAKy/PLygmg0io2NjQymWm3Hq6BbXl6O19dXIzQD8/PzsbKyIppq5SkFN6EdHBygu7sbb29v+Pr6kjVptUQi4TY2NmZowXQmJycxOzsrjgRi2ly3e3RtbQ3Dw8NmQ/kWj8fdjo4OUwStGvUsLS3NaFzVUtPju7LXtnKOjo7c1tZW0xpawfPzc9TW1gojBjGtvLw88dO16+trVFdXm5Tp55ycnLgcJWrmVdxo0dXVhe3tbTN+NhMF5ACEQiHRVTeVKldVVYG7qWlwT08PlpeXZX7tZn58fMTExATC4XBG4wtDAk5PT2NmZsboZTdxWVkZmpqazIFwcXGBWCwGgmZPDpk6Hn2XAEz79PTUpKyCMz068k7LbnbqSn3pU1FRAcdrCZdUz87O0NnZidvbWwm0NbWlUGD7O0H9fj+8AqdTVqfj42P09vYimUwKE+7KuxZB2doHBjfjibO7u4uampo0oE4Ag5+fnzE3N4eFhQU8PT0ZYAWxTxhmxklaWlpCUVFRuum9ILekpETOPJ59avf399jb25MCpFIpXF5eSlvV19dLw7e3t2N0dBSFhYVSTO0Mnt9uW1sbpqamEAwGpXLZx7rdzHZRVAIdT6myZ+a3wrmcn58XBirDXxOimupG+v/h+z9biQLDtWi4nwAAAABJRU5ErkJggg=='
var param3 = params + params2;
console.log(param3);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(param3);
works like a charm, the problem start when i tried to implement that on the current code that converts a captured image from screen in blob format to base64 string, i only get the error from api 'invalid base64 string' using the exact same code above, JS is generating a invalid base64??
using some base64 to image online everything seams ok, but the same string on code only returns invalid base64 string
example of image refused as invalid:
iVBORw0KGgoAAAANSUhEUgAAAG4AAABDCAYAAAB9aTATAAAHpElEQVR4Xu1dy24cVRDt+QZ7zB8ksQ3sQSYhiC0CkigirMICRLIgLAgSCMlECiACCx6SEwWksAIEgSDYIkIegj3gV/4Aj/0NA6eV06op31t1u8ft7kj3bpKZvl236pz7mJ46rhmsbWyOP7/8ZbHyyaUC7cL7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2XiuuegkQeZuEawdX9TJq57Dhp5kIlrBFv3N2XiuuegkQeZuEawdX9TJq57Dhp5kIlrBFv3N2XiuuegkQcVcbECNKEvkeuM1GdlV504uuqr5Y/kY+KP92UVIDo6LfDT3t8VYH0dd4I4mc+qm3bxAszEeQjVuz5BHIU2SPqhUbGlf+vMKzZGkmRRNU2cVl9ZMrSQvToF1PZL2mdJBUM/zyZ/isyTGYYS1eCo3CqZNp+bnY3+0lJKYTBNCgaQxGkllSdD0/bqFFDbT2mfJRXUk19j4skMY8T9B/qsYv/FWKeaAAAAAElFTkSuQmCC
how i am converting blob to base64:
console.log("init try upload to Snipboard");
console.log(image_data)
console.log(image_data.imgBlob)
var imgBlob = image_data.imgBlob;
var reader = new FileReader();
var base64data = null;
reader.readAsDataURL(imgBlob);
reader.onloadend = function()
{
base64data = reader.result;
console.log("blob to base64: " + base64data);
var base64Image = base64data.replace(/^.*,/, '');
console.log("blob to base64 pure: " + base64Image);
addon.make.upload(image_data, base64Image);
}
and in addon.make.upload(image_data, base64Image); there is the above XMLHttpRequest code that returns 'invalid base64 string'
anyone has any ideas how convert blob to base64 string....valid?
or what i am doing wrong?

Taking an image and converting it into BLOB for MySQL

I am trying to make a JavaScript that would take an image file and covert it into BLOB (by converting the file into Base64 first and then into BLOB), my project doesn't have a support for toBlob() so I have found different convering steps and put them together and they work to a point where I have to pass the BLOB from the function where its made out for the Mysql part of code that takes care of communicating with the database. (I have that fully working). Now I only need to find a way how to connect them through a variable that saves the results of the imageforQuery function.
My code so far is this:
let base64String = "";
function imageforQuery(imageid) {
//takes file and converts to Base64
var file = document.getElementById(imageid).files[0];
var reader = new FileReader();
console.log("next");
imgFileFrontBlob = "";
reader.onload = function () {
base64String = reader.result.replace("data:", "")
.replace(/^.+,/, "");
// console.log(base64String);
base64String = 'data:image/jpeg;base64,'+ base64String;
console.log(base64String);
//converts Base64 into BLOB
var binary = atob(base64String.split(',')[1]);
console.log(binary);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
var imgFileFrontBlob = new Blob([new Uint8Array(array)], {type: 'image/png'});
console.log(imgFileFrontBlob);
return imgFileFrontBlob
}
reader.readAsDataURL(file);
};
by experimenting with console.log() at different stages and return I have found out that I can't pass the converted BLOB result out, as the function imageforQuery() only returns what is after reader.readAsDataURL(file); and I don't know of a way of getting that result out.
––––––––––––––ADDITIONAL PROBLEMS I HAVE ENCOUNTERED––––––––––––––
okay so thanks to Emiel Zuurbier (Thank you!) I have managed to rewrite my code with the help of his solution. However as much as it helped one part of the problem, it didn't help with the JavaScript Blob object as we found out it is not the exact same thing as SQL BLOB.
Now the problem is that upon trying to send the Blob object in a SQL query, this resulted in just sending pure text "[Blob object]".
But I am using JavaScript successfully to pull the data from a BLOB field from my database and convert it into Base64 images from that data that was stored in the BLOB in a different part of my application. The code for that is below:
var converterEngine = function (input) {
// fn BLOB => Binary => Base64 ?
var uInt8Array = new Uint8Array(input),
i = uInt8Array.length;
var biStr = []; //new Array(I);
while (i--) { biStr[i] = String.fromCharCode(uInt8Array[i]); }
var base64 = window.btoa(biStr.join(''));
return base64;
};
What I need to do is just reverse this and in theory, it should get me the same data that I receive from the database.
My reversal code is below:
// this is the inside bit of code from the first problem that is solved and the
// typeOfData variable is parsed into the function in imageforQuery() as a second input
// variable (in other words its not to be of concern)
reader.onload = function () {
let base64String = reader.result.replace("data:", "").replace(/^.+,/, "");
base64String = "data:" + typeOfData + ";base64," + base64String;
var binary = atob(base64String.split(",")[1]);
// console.log(binary);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
var ourArray = new Uint8Array(array);
resolve(ourArray);
};
However, as I mentioned the data that comes out (ourArray) isn't actually identical to the original file from the BLOB in the database so my code doesn't function correctly and I don't know why. Any ideas where I've made a mistake?
Base64 is simply ascii text. So MySQL's datatype BLOB or TEXT would work. That is, after converting to Base64, don't worry about "convert to blob"; it is not necessary.
That is, you can probably replace the code from //converts ... through return ... by simply
return base64String;
You can wrap the FileReader instance and calls inside of a Promise. Return the Promise immediately. In the reader.onload function call resolve() to exit the Promise with a value.
function imageforQuery(imageid) {
return new Promise(resolve => {
var file = document.getElementById(imageid).files[0];
var reader = new FileReader();
reader.onload = function () {
let base64String = reader.result.replace("data:", "").replace(/^.+,/, "");
base64String = "data:image/jpeg;base64," + base64String;
var binary = atob(base64String.split(",")[1]);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
var imgFileFrontBlob = new Blob([new Uint8Array(array)], {
type: "image/png",
});
resolve(imgFileFrontBlob);
};
reader.readAsDataURL(file);
});
}
This results in being able to use your function like here below. imageforQuery is called, returns a Promise. When the promise is finished (meaning resolve is called) the function in the then method will run.
imageforQuery(imageId).then(imgFileFrontBlob => {
// Use your blob here.
saveToDB(imgFileFrontBlob); // Example of how you would use it.
});
Or use it with async / await.
(async () => {
function imageforQuery(imageid) {
...
}
// Here we can wait for imageforQuery to finish and save the variable.
const imgFileFrontBlob = await imageforQuery(imageId);
saveToDB(imgFileFrontBlob); // Example of how you would use it.
})()

Convert a Base64 image string back into a file to send to Parse upload

Adding CropperJS into a nodejs solution, and I'm trying to get the returned Base64 string back into file format. So I can send the file to the upload function.
I can't change any functionality and need to use file type to send as a parameter.
I tried: Creating a blob and passing it -> get an error can't to parse the file.
//this is used to upload the file
File.upload(file).then(function (savedFile) {
//with the new cropper i get back base64 string from:
$scope.imgSrc = $scope.cropperCrop.getCroppedCanvas().toDataURL();
How do I convert imgSrc to file to pass into the File upload function?
You can use this function to convert Base64 image string to image/file object.
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//Usage example:
var base64String = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQ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I6qcYuEW4pvXdJ/afc//Z"
var file = dataURLtoFile(base64String, 'filename.png');
console.log(file);

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

Store image content not image path in mongodb

I have seen many questions and solutions for this now. I am new to Mongo DB and MEAN stack development. I want to know whether there is anyway to store image content itself rather than path of the image file in Mongo DB. All the solutions suggests to store image as buffer and then use it back in the source by converting buffer to base64. I did it but the resulting output get resolves to path to the image file rather than the image content. I am looking to save image itself in DB.
// saving image
var pic = {name : "profilePicture.png",
img : "images/default-profile-pic.png",
contentType : "image/png"
};
//schema
profilePic:{ name: String, img: Buffer, contentType: String }
//retrieving back
var base64 = "";
var bytes = new Uint8Array( profilePic.img.data );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
base64 += String.fromCharCode( bytes[ i ] );
}
var proPic = "data:image/png;base64," + base64;
console.log(proPic);
//console output
data:image/png;base64,images/default-profile-pic.png
The output for proPic resolves to "data:image/png;base64,images/default-profile-pic.png"
few links that I referred before posting this
How to do Base64 encoding in node.js?
How to convert image into base64 string using javascript
The problem is simply, that you don't read and encode the picture. Instead you use the path as a string.
Serverside using Node
If you want to perform it on the serverside with an image on the filesystem you can use something along following:
var fs = require('fs');
// read and convert the file
var bitmap = fs.readFileSync("images/default-profile-pic.png");
var encImage = new Buffer(bitmap).toString('base64');
// saving image
var pic = {name : "profilePicture.png",
img : encImage,
contentType : "image/png"
};
....
Clientside
Again we need to load the image and encode it as base64. There is an answer about doing this on the client here.
using the first approach the result would be something like following:
function toDataUrl(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
toDataUrl("images/default-profile-pic.png", function(encImage){
// saving image
var pic = {name : "profilePicture.png",
img : encImage,
contentType : "image/png"
};
//Proceed in the callback or use a method to pull out the data
....
});
Below two links saved my time. If we use "ng-file-upload" our life becomes easy from there.
https://github.com/danialfarid/ng-file-upload#install
https://github.com/danialfarid/ng-file-upload
Below is what worked for me
//my html code
<div>
<button type="file" ngf-select="onFileSelect($file)" ng-model="file" name="file" ngf-pattern="'image/*'"
ngf-accept="'image/*'" ngf-max-size="15MB" class="btn btn-danger">
Edit Profile Picture</button>
</div>
//my js function
function onFileSelect(file){
//var image = document.getElementById('uploadPic').files;
image = file;
if (image.type !== 'image/png' && image.type !== 'image/jpeg') {
alert('Only PNG and JPEG are accepted.');
return;
}
$scope.uploadInProgress = true;
$scope.uploadProgress = 0;
var reader = new window.FileReader();
reader.readAsDataURL(image);
reader.onloadend = function() {
base64data = reader.result;
$scope.profile.profilePic = base64data;
ProfileService.updateProfile($scope.profile).then(function(response){
$rootScope.profile = response;
$scope.profilePicture = $rootScope.profile.profilePic;
});
}
}
// when reading from the server just put the profile.profilePic value to src
src="data:image/png;base64,{base64 string}"
// profile schema
var ProfileSchema = new mongoose.Schema({
userid:String,
//profilePic:{ name: String, img: Buffer, contentType: String },
profilePic:String
}
I wouldn't say this is the best solution but a good place to start.Also this limits you from uploading file size more than 16 MB in which case you can use"GridFs" in the above implementation initially the file is converted to "blob" and then I am converting it to "base64" format and adding that to my profile's string variable.
Hope this helps someone in saving their time.

Categories

Resources