HTML

<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">

JavaScript

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/?[A-z]*;base64,/);
}

var base64 = getBase64Image(document.getElementById("imageid"));

Special thanks to @Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!

This method requires the canvas element, which is perfectly supported.

  • The MDN reference of HTMLCanvasElement.toDataURL().
  • And the official W3C documentation.
Answer from ˈvɔlə on Stack Overflow
🌐
Tick
pqina.nl › blog › convert-a-file-to-a-base64-string-with-javascript
Convert A File To A Base64 String Or DataURL Using JavaScript - Pqina
<input type="file" /> <script> // Get a reference to the file input const fileInput = document.querySelector('input'); // Listen for the change event so we can capture the file fileInput.addEventListener('change', (e) => { // Get a reference to the file const file = e.target.files[0]; // Encode the file using the FileReader API const reader = new FileReader(); reader.onloadend = () => { // Use a regex to remove data url part const base64String = reader.result .replace('data:', '') .replace(/^.+,/, ''); console.log(base64String); // Logs wL2dvYWwgbW9yZ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › FileReader › readAsDataURL
FileReader: readAsDataURL() method - Web APIs | MDN
September 18, 2025 - const preview = document.querySelector("img"); const fileInput = document.querySelector("input[type=file]"); fileInput.addEventListener("change", previewFile); function previewFile() { const file = fileInput.files[0]; const reader = new FileReader(); reader.addEventListener("load", () => { // convert image file to base64 string preview.src = reader.result; }); if (file) { reader.readAsDataURL(file); } }
Discussions

javascript - Convert image from url to Base64 - Stack Overflow
Using an Image File, I am getting the url of an image, that needs be to send to a webservice. From there the image has to be saved locally on my system. The code I am using: var imagepath = $("# More on stackoverflow.com
🌐 stackoverflow.com
html - How to convert Base64 String to javascript file object like as from file input form? - Stack Overflow
So I want to convert a base64 string to the javascript file object like that. I just want to get file object by decoding base64 string (encoded by other app from a file) without html file input form. ... Save this answer. ... Show activity on this post. Way 1: only works for dataURL, not for other types of url... More on stackoverflow.com
🌐 stackoverflow.com
How to convert file to base64 in JavaScript? - Stack Overflow
I need to open this Base64 file in browser with the same file name, i am opening it using window.open(url, '_blank') which is working fine, how can i give file name to that ? please help. More on stackoverflow.com
🌐 stackoverflow.com
File to Base64 with JavaScript - App Showcase - MIT App Inventor Community
In this example, you will learn to write a JavaScript program that will encode a string to Base64 · This has promise Does the readTextFileAsBlob function also work for other file types, e.g. image, pdf, zip · I have decoded it using javascript, but the decoded results are not as expected, ... More on community.appinventor.mit.edu
🌐 community.appinventor.mit.edu
0
August 2, 2022
🌐
Medium
shivamethical.medium.com › convert-local-url-url-to-base64-in-javascript-a77a1e40833d
Convert local URL(URL) to Base64 in javascript | by Shivam Gupta | Medium
November 19, 2019 - Convert local URL(URL) to Base64 in javascript Use XMLHttpRequest() set responseType to Blob , use FileReader() at XMLHttpRequest onload event to read response as data URI var xhr = new …
🌐
Base64.Guru
base64.guru › home › developers › javascript › examples
Encode remote file to Base64 in JavaScript | Examples | JavaScript | Developers | Base64
To encode a remote file on Base64 to Javascript, you must have its URL address, and if it is not a relative URL, make sure that CORS header “Access-Control-Allow-Origin” is not missing, otherwise you’ll face the “Cross-Origin Request Blocked” error.
Top answer
1 of 10
342

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[arr.length - 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,aGVsbG8=','hello.txt');
console.log(file);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

// return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
    if (url.startsWith('data:')) {
        var arr = url.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[arr.length - 1]), 
            n = bstr.length, 
            u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        var file = new File([u8arr], filename, {type:mime || mimeType});
        return Promise.resolve(file);
    }
    return fetch(url)
        .then(res => res.arrayBuffer())
        .then(buf => new File([buf], filename,{type:mimeType}));
}

//Usage example:
urltoFile('data:text/plain;base64,aGVsbG8=', 'hello.txt','text/plain')
.then(function(file){ console.log(file);});
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 10
121
const url = 'data:image/png;base6....';
fetch(url)
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], "File name",{ type: "image/png" })
  })

Base64 String -> Blob -> File.

🌐
Talkerscode
talkerscode.com › howto › convert-image-url-to-base64-javascript-without-canvas.php
Convert Image URL To Base64 JavaScript Without Canvas
There creating file reader object ‘reader’ then we appending reader with ‘readAsDataURL()’ method for reads whole content of blob file when finish it triggers onloadend event. This event waiting for return result then when it gets result we send it to callback method then printed on console. <!DOCTYPE html> <html> <head> <title>GET IMAGE AS BASE64 URL WITHOUT CANVAS</title> </head> <body> <script> function getimgBase64(url,callback){ var xhr=new XMLHttpRequest(); xhr.onload=function(){ var reader=new FileReader(); reader.onloadend=function(){ callback(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET',url); xhr.responseType='blob'; xhr.send(); } getimgBase64('https://assets.entrepreneur.com/content/3x2/2000/1602623277-GettyImages-1204099658.jpg', function(dataUrl){ console.log('RESULT:',dataUrl); }); </script> </body> </html>
Find elsewhere
🌐
Base64 Encode
base64encode.org
Base64 Encode and Decode - Online
Enable this option to encode into an URL- and filename- friendly Base64 variant (RFC 4648 / Base64URL) where the "+" and "/" characters are respectively replaced by "-" and "_", as well as the padding "=" signs are omitted.
🌐
Medium
medium.com › @simmibadhan › converting-file-to-base64-on-javascript-client-side-b2dfdfed75f6
Converting file to base64 on Javascript client side | by Simmi Badhan | Medium
July 1, 2020 - // Convert file to base64 string 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 ...
🌐
MIT App Inventor
community.appinventor.mit.edu › app showcase
File to Base64 with JavaScript - App Showcase - MIT App Inventor Community
August 2, 2022 - To convert a String to/from Base64 in JavaScript, we use the btoa and atob commands. Here is another code to convert a file to Base64: ToBase64.htm <script> async function readTextFileAsBlob(file) { const respo…
🌐
GitHub
gist.github.com › matinrco › 563dfa706a338c0e6be60378541bc1b7
Convert any file to base64 in javascript · GitHub
Convert any file to base64 in javascript . GitHub Gist: instantly share code, notes, and snippets.
🌐
Base64.Guru
base64.guru › home › developers › javascript › examples
Encode form file to Base64 in JavaScript | Examples | JavaScript | Developers | Base64
I hope you enjoy this discussion. In any case, I ask you to join it. ... If you submit reader.result as content it will send base64 data + file type at the beginning.
🌐
codestudy
codestudy.net › blog › convert-image-from-url-to-base64
How to Convert Image URL to Base64 in JavaScript: Step-by-Step Guide for Local Saving — codestudy.net
CORS Handling: Base64 encoding itself cannot bypass cross-origin restrictions. When using Canvas to export image data, the server must allow CORS via appropriate headers for the operation to succeed. ... Basic JavaScript Knowledge: Familiarity with promises, async/await, and DOM manipulation. HTML5 Understanding: Awareness of the <canvas> element and Blob/File APIs. Tools: A code editor (e.g., VS Code), a modern browser (Chrome, Firefox, Edge), and an image URL for testing (e.g., https://example.com/image.jpg).
🌐
Base64
base64.sh › blog › base64-javascript-examples
Base64 in JavaScript - Practical Examples | Base64.sh
// Convert file to Base64 data URI function fileToBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); reader.readAsDataURL(file); }); } // Usage with file input ...
🌐
Base64 Decode
base64decode.org
Base64 Decode and Encode - Online
This combination leaves the data unlikely to be modified in transit through systems such as email, which were traditionally not 8-bit clean. For example, MIME's Base64 implementation uses A-Z, a-z, and 0-9 for the first 62 values, as well as "+" and "/" for the last two. Other variations, usually derived from Base64, share this property but differ in the symbols chosen for the last two values; an example is the URL and filename safe "RFC 4648 / Base64URL" variant, which uses "-" and "_".
🌐
GiftOfSpeed
giftofspeed.com › base64-encoder
File To Base64 Converter | Encode any file
Convert your website's smaller files to Base64 to reduce the number of HTTP requests.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-image-into-base64-string-using-javascript
Convert image into base64 string using JavaScript - GeeksforGeeks
February 25, 2026 - <!DOCTYPE html> <html> <head> <title> How to convert image into base64 string using JavaScript ? </title> </head> <body> <input type="file" name="" id="fileId" onchange="imageUploaded()"> <br><br> <button onclick="displayString()"> Display String </button> <script> let base64String = ""; function imageUploaded() { let file = document.querySelector( 'input[type=file]')['files'][0]; let reader = new FileReader(); console.log("next"); reader.onload = function () { base64String = reader.result.replace("data:", "") .replace(/^.+,/, ""); imageBase64Stringsep = base64String; // alert(imageBase64Stringsep); console.log(base64String); } reader.readAsDataURL(file); } function displayString() { console.log("Base64String about to be printed"); alert(base64String); } </script> </body> </html>
🌐
CodePen
codepen.io › AshV › pen › pjodjV
Convert File to base64
You can use the URL of any other Pen and it will include the JavaScript from that Pen.