I have the following Javascript-Code for Converting a file into base64:
File.prototype.convertToBase64 = function (callback) {
var FR = new FileReader();
FR.onload = function (e) {
callback(e.target.result)
};
FR.readAsDataURL(this);
}
an example output would be:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj [...] /j+vigYmLtYx9n0tGzJIyZKIzsYyRRWj0RfdWtCiQdF9rH8f18SMciL7X8DJMySJ8uC4JDRWjH8CEiitULVaMf68GQYn2PvskyciSs26tDWr0ooorsWi0WiFIei0Y/10QkQkWWXo+xaNjetdjHo9YlFdi1eiell6LRj/AGIshIUjcKRej1Ws
But I can't decode it with this:
byte[] data = Convert.FromBase64String(base64Image);
It says that it can't recognize the layout of the data. How can I decode the base64 data coming from FileReader in JS in C#?
Thanks to Thomas I found a solution.
The C#-Decoder doesn't like the header: data:image/jpeg;base64,
You can fix it with this short code:
int index = base64Image.IndexOf("base64,") + "base64,".Length;
string base64String = base64Image.Remove(0, index);
Related
I'm working on a REST web application that manages documents between users and uploaders. The backend is written in Java and my Document entity contains, besides various attributes, a byte[] content. I was able to send a file created at server side by
#GET
...
document.setContent(Files.readAllBytes(Paths.get("WEB-INF/testFile.txt")));
return Response.ok(document).build();
and retrieve it at front-end (vueJs) through
async function download(file) {
const fileURL = window.URL.createObjectURL(new Blob([atob(file.content)]));
const fileLink = document.createElement("a");
fileLink.href = fileURL;
fileLink.setAttribute("download",`${file.name}.${file.type}`);
document.body.appendChild(fileLink);
fileLink.click();
fileLink.remove;
window.URL.revokeObjectURL(fileURL);
}
the problem is that when I try to upload a file and then download it, its content is not parsed correctly (is shown undefined, string in Base64 or numbers depending on how I try to solve it). The file is sent by a post request and is retrieved through an input form bound to an onFileSelected function.
function onFileSelected(e) {
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onloadend = (evt) => {
if (evt.target.readyState === FileReader.DONE) {
var arrayBuffer = evt.target.result;
this.file.content = new Uint8Array(arrayBuffer);
//this.file.content = arrayBuffer;
}
};
}
axios.post(...,document,...)
and I have tried using atob and btoa as well before assigning the value to this.file.content. If I print the file on server Welcome.txt it gives B#ae3b74d and if I use Arrays.toString(welcome.getContent()) it gives an array of numbers but as soon as it passed to the frontend its content become in Base64 welcome: { ... content: IFRoaXMgaXMgYSB0ZXN0IGZpbGUhIAo...}. Any idea? Thank you a lot!
I have a file uploader input, where I accept a file, convert it to base 64 string, and send the payload to a rest api.
However, when I was encoding base64 for utf-8 files, it was working fine. But if I try to get base64 strings of "window-1251" files, it is not converted to a string properly, and the api throws error instead because the base64 string is not valid content.
So my question is how do I get base64 string of a file that uses window-1251 for encoding?
var reader2 = new FileReader();
reader2.readAsDataURL(file);
reader2.onload = function (e) {
var sContentStream = e.target.result;}
Sorry, but the premise makes no sense.
FileReader.readAsDataURL will always return a valid base64 string from what you gave to it => binary data.
The fact that these bytes represent a text file, with a given encoding is simply ignored by the algorithm.
const rand_data = crypto.getRandomValues(new Uint8Array(50));
const blob = new Blob([rand_data]);
const reader = new FileReader();
reader.onload = e => {
const dataURL = reader.result
const base64 = dataURL.slice(dataURL.indexOf(',')+1);
console.log(base64);
console.log(atob(base64)); // would throw if invalid data
};
reader.readAsDataURL(blob);
So you are looking at the wrong end of the problem: The consumer may have issues with reading windows-1251 encoded text files, but that's not FileReader's fault.
Now, if you are willing to do the conversion from this encoding to UTF-8 in the browser, then that's still doable, but you's need a way to know which encoding the file you've been given is in.
const win_1251 = new Blob([Uint8Array.from([200])]); // И in windows-1251
// to prove it's not UTF-8
readUTF8Text(win_1251); // �
const reencode_reader = new FileReader();
reencode_reader.onload = e => {
const utf_8_arr = new TextDecoder('windows-1251')
.decode(new Uint8Array(reencode_reader.result));
const utf_8 = new Blob([utf_8_arr], {type: 'text/plain'})
makeDataURL(utf_8);
readUTF8Text(utf_8); // И
};
reencode_reader.readAsArrayBuffer(win_1251);
function makeDataURL(blob) {
const reader = new FileReader();
reader.onload = e => {
console.log(reader.result);
};
reader.readAsDataURL(blob);
}
function readUTF8Text(blob) {
const reader = new FileReader();
reader.onload = e => {
console.log(reader.result);
};
reader.readAsText(blob);
}
I am trying to convert an image to base64 to upload it on sharepoint site but it is throwing 400:bad request error. when i checked properly then i found out that the base64 i am sending is endcoded by javascript and it is different than what is expected by sharepoint. I have attached 2 images here describing the difference. Can anyone help me to get the proper encoded data using javascript ?
javascript encoded base64
c# encoded base64
var files = $("#myfile").get(0).files;
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function () {
console.log(reader.result);
}
Could try : reader.result.split("base64,")[1]
Removes the "base64," start of the string.
Please try this , i am using this in my project , its working for me
if (file.ContentType.Contains("image"))
{
string theFileName = Path.GetFileName(file.FileName);
byte[] thePictureAsBytes = new byte[file.ContentLength];
using (BinaryReader theReader = new BinaryReader(file.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
}
"thePictureDataAsString " variable got Base64 string
.........................................................................
i am getting file like this in my project
public ActionResult SaveMake(string inputMakeName, HttpPostedFileBase file)
{
MakeModel objMakeModel = new MakeModel();
if (file.ContentType.Contains("image"))
{
string theFileName = Path.GetFileName(file.FileName);
byte[] thePictureAsBytes = new byte[file.ContentLength];
using (BinaryReader theReader = new BinaryReader(file.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
objMakeModel.ImageBase64 = thePictureDataAsString;
objMakeModel.Make1 = inputMakeName;
}
string response = _apiHelper.ConvertIntoReturnStringPostRequest<MakeModel>(objMakeModel, "api/Transaction/SaveMakes/");
// string response = _apiHelper.SaveMake(objMakeModel, "api/Transaction/SaveMakes/");
return RedirectToAction("AddVehicleMaintenance");
}
I want to convert audio file into base64 using Javascript only.
We can convert images into base64 using canvas. But how can we convert audio files.
Any help will be grateful.
you can give the below code a try, it uses btoa
function getData(audioFile, callback) {
var reader = new FileReader();
reader.onload = function(event) {
var data = event.target.result.split(',')
, decodedImageData = btoa(data[1]); // the actual conversion of data from binary to base64 format
callback(decodedImageData);
};
reader.readAsDataURL(audioFile);
}
Here's how to convert an audio file to a base64 string with JavaScript:
async function audioToBase64(audioFile) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onerror = reject;
reader.onload = (e) => resolve(e.target.result);
reader.readAsDataURL(audioFile);
});
}
You can use it like this:
<input oninput="audioToBase64(this.files[0]).then(result => console.log(result))" type="file">
This will console.log a string like data:audio/mpeg;base64,//uYxAAAAA... when a file is chosen in that filepicker.
Here i want to get the Data from Excel File by using upload file control.My Snippet is
window.onload = function () {
var fileInput = document.getElementById('fup1');
var fileDisplayArea = document.getElementById('txt1');
fileInput.addEventListener('change', function (e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function (e) {
txt1.innerText = reader.result;
}
reader.readAsText(file);
});
}
when i run this code i get the data in below format
PK!q9+p��[Content_Types].xml ��(�̔MN�0��H�!�%n��j�?K��ؓƪc[���g��
P�T��DQ4���f��|[�d��9g#���Ni�����Cz���*a�����|v~6}�y���-欌��p���J`�
how can i resolve this please help me
First of all you have to understand what you are doing. You are taking a exel file( which is not in a txt format) converting it into fileStream( buffer of bytes) finally you are converting it into txt file( which was a exel file). So what do you expect the result.
Now try Solving this problem using two popular JavaScript libraries:
1. xls
2. xlsx
Which allow you to parse in pure JavaScript.
For Documentation of these two libraries you can refer to following link.
Documentation