Get Base64 Encode File-Data from Input Form

Get Base64 encode file-data from Input Form

It's entirely possible in browser-side javascript.

The easy way:

The readAsDataURL() method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,), but that's no biggie. This would take all the fun out though.

The hard way:

If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer(). This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.

There are two methods:

  • Convert to string and use the built-in btoa or similar
    • I haven't tested all cases, but works for me- just get the char-codes
  • Convert directly from a Uint8Array to base64

I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's here if you want to take a look; it's pretty neat.

What I do now:

The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):

function uint8ToString(buf) {
var i, length, out = '';
for (i = 0, length = buf.length; i < length; i += 1) {
out += String.fromCharCode(buf[i]);
}
return out;
}

From there, just do:

var base64 = btoa(uint8ToString(yourUint8Array));

Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:

window.open("data:application/octet-stream;base64," + base64);

This will download it as a file.

Other info:

To get the data as a Uint8Array, look at the MDN docs:

  • https://developer.mozilla.org/en/DOM/FileReader

How to convert file to base64 in JavaScript?

Modern ES6 way (async/await)

const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});

async function Main() {
const file = document.querySelector('#myfile').files[0];
console.log(await toBase64(file));
}

Main();

UPD:

If you want to catch errors

async function Main() {
const file = document.querySelector('#myfile').files[0];
try {
const result = await toBase64(file);
return result
} catch(error) {
console.error(error);
return;
}
//...
}

getting base64 string from html file upload element

UPDATED Answer for HTML5 and IE without HTML5

you need to use FileReader.readAsDataURL() instead see js fiddle example

function getImage() {
var reader = new FileReader(); var f = document.getElementById("file-select").files;
reader.onloadend = function () { console.log(reader.result); } reader.readAsDataURL(f[0]);
}
<form id="file-form" method="POST">    <input type="file" id="file-select" /></form><button onclick="getImage()" id="upload-button">Convert</button>

How to convert Base64 String to javascript file object like as from file input form?

Way 1: only works for dataURL, not for other types of url.

 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 file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');    console.log(file);

How to input image file from user and then base64 encode it in javascript?

Here's a simple example converting the first image selected using the file browse button. File reading occurs on the client side after an image has been selected. File reading is asynchronous so I've promisified the file reading function:

"use strict";
const fileDataURL = file => new Promise((resolve,reject) => { let fr = new FileReader(); fr.onload = () => resolve( fr.result); fr.onerror = reject; fr.readAsDataURL( file)});
function showResult(file) { fileDataURL( file) .then( data => (document.getElementById("result").textContent = data)) .catch(err => console.log(err));}
#result {   width: 80%;   font-family: monospace;   overflow-wrap: break-word;}
<p><input type="file" onchange="showResult( this.files[0]);" accept="image/*"><div>Data URL:</div><div id="result"></div>

How to get base64 img src and insert it into input.files

You need convert base64 image to file, then use DataTransfer to recivie the file. You can try my sample code like below.

@{
ViewData["Title"] = "Home Page";
}
@model Net5_MVC.Controllers.HomeController.mainImageInput
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script>
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 });
}
function ConvertClick(base64url) {
var file = dataURLtoFile(base64url, "test.png");
let container = new DataTransfer();
container.items.add(file);
document.querySelector('#mainImageInput').files = container.files;
var newfile = document.querySelector('#mainImageInput').files[0];
}
</script>

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<img id="mainImage" style="width:200px;height:160px" src="@Model.ImageInBase64">

<input asp-for="Image" id="mainImageInput" style="display:none" type="file" accept="image/jpeg, image/png" class="form-control" />
<button onclick="ConvertClick('@Model.ImageInBase64')">Convert</button>

Test Result:

Sample Image



Related Topics



Leave a reply



Submit