Is there a way to encode a local file to base64 without using XMLHttpRequest in JavaScript?

I'm attempting to encode a local file using base64. The file is located next to my .js file, so there is no need for uploading. I've tried solutions like the one mentioned in this link (using XMLHttpRequest), but it resulted in a cross-site scripting error.

I have also experimented with code similar to this snippet below (which unfortunately does not work, but may help clarify my issue):

var file = 'file.jpg'
var reader = new FileReader();
reader.onload = function(e) {
   var res = e.target.result;
   console.log(res);
};
var f = reader.readAsDataURL(file);

Has anyone encountered success in performing this locally before?

Answer №1

Methods like this (using XMLHttpRequest) result in a cross-site scripting error.

If you are using the chrome or chromium browser, you can start with the --allow-file-access-from-files flag enabled to allow requests for resources from the local file system using XMLHttpRequest() or canvas.toDataURL().

You have the option to use the <img> element, <canvas> element, and .toDataURL() method to generate a data URL of a local image file without relying on XMLHttpRequest().

var file = "file.jpg";
var img = new Image;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
img.onload = function() {
  canvas.width = this.naturalWidth;
  canvas.height = this.naturalHeight;
  ctx.drawImage(this, 0, 0);
  var res = canvas.toDataURL("image/jpeg", 1); // specify image `type` as `image/jpeg`
  console.log(res);
}
img.src = file;

An alternative approach is to utilize XMLHttpRequest() as explained in Convert local image to base64 string in Javascript.

Refer to How to print all the txt files inside a folder using java script for more information.


To understand the differences in the returned data URI from each approach, consult canvas2d toDataURL() different output on different browser

As stated by @Kaiido in this comment below

the process involves decoding the file, then painting it onto the canvas as raw pixels before encoding it again. This results in completely different dataURI strings. Even if the same canvas operation is performed on two different browsers, the outputs will differ, unlike with FileReader, which consistently produces the same output by directly encoding the file without decoding it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve the position of a descendant element in relation to its ancestor element

I'm encountering a challenge while attempting to solve this issue. I have elements representing a child, parent, and grandparent. My goal is to determine the offset position of the child (positioned absolutely) in relation to the grandparent. However, ...

Implementing a personalized Angular filter with an indexOf condition

As a beginner in the world of computers, I am attempting to create a customized filter for an AngularJS application. My objective is to search through a string of integers (cultivos.age) and retrieve the item if the string meets the mes.age condition. I h ...

Establish a WebSocket connection via Meteor.js

How do we establish a Websockets connection in Meteor? Can we achieve this using the following code: ws = new WebSocket('ws://localhost/path'); ws.on('open', function() { ws.send('something'); }); ws.on('message&apo ...

What is the best way to determine the width of a div within a window that has been rendered using React?

I'm working on a task where I need to determine the size of a div (with CSS width set to 100%) and adjust the zoom factor of a component based on this size. The challenge arises during the initial run of the application when the div has not yet been c ...

What is the best way to display a pop-up notification once a user has successfully logged in?

I'm currently developing a website using asp.net core mvc for an assignment. The website features identity server for user authentication. I am attempting to display a pop-up alert once a user enters the correct login credentials and clicks the Login ...

The focus state persists even after the DOM element has been modified

I am currently utilizing Vue along with Bulma. My challenge lies in updating the DOM upon a button click event. Even after the update, the button still retains its focus state. I aim to have the updated button without the focus state. What would be the m ...

Tips on extracting the value from the chosen option in 2 separate rows with identical IDs

While looping through my table, each row is identified by the id="batchNo". I am trying to retrieve the selected value of each select option in every row. Although I attempted to achieve this with the provided code snippet, it only retrieves the selected ...

Running intricate javascript/jquery/json code using an html checkbox

Hey there, I'm hoping this issue is simpler than I'm making it out to be... So, I've got this pretty complex JSON/jQuery function (3000 lines long) that builds a DOM tree in a separate JS file. This JS file also contains a bunch of other on ...

Is it correct that when values are saved without being paired with keys, they are stored as keys within a JavaScript object?

Consider a scenario where you have an object: const obj = { time, difficulty, distance, } Are the values inside the object saved as keys? If I were to use Object.keys() on the object, would I get an array of individual string elements? ...

The JSON file gets emptied every time I refresh the page repeatedly

I am encountering an issue where my JSON file gets cleared if I restart the page quickly after using the fs module to read/write it. The JSON data is read at the beginning of the page like this: let preferencesJSON; try { preferencesJSON = fs.readFile ...

Is there a way to retrieve the list element that was added after the HTML was generated?

How can I reference a list element added using the append function in jQuery within my onclick function? See my code snippet below: $(function() { let $movies = $('#showList') let $m = $('#show') $.ajax({ method: 'GET ...

How does the browser respond when the iframe source is set to javascript?

Have you ever wondered about the source of an iframe when it looks like this: javascript:''; Take a look at this example: <iframe id="SpControlFrame1" name="SpControlFrame1" src="javascript:'';" path_src="index.php?cmd=YYY" >&l ...

Revising Global Variables and States in React

Recently delving into React and tackling a project. I find myself needing to manage a counter as a global variable and modify its value within a component. I initialized this counter using the useState hook as const [currentMaxRow, setRow] = useState(3) ...

Determine which array within an object is the longest in terms of length

Currently, I'm incorporating lodash.js into my project but it seems that there is no built-in method to achieve what I need. Even after attempting it on my own, I find myself dissatisfied with the outcome. function findLargestArrayInObject(object) ...

Run JavaScript code that is retrieved through an ajax request in Ruby on Rails

When I use Rails to render a javascript view, the code looks like this: $("##{@organization.id}-organization-introtext").hide(); $("##{@organization.id}-organization-full").append("#{escape_javascript(render @organization)}").hide().fadeIn('slow&apos ...

Angular SPA boasting an impressive one million pages

Currently, I am in the process of transitioning my webshop, which contains numerous products, to an Angular SPA application using ngRoute and HTML5 mode. I have come up with a method where I receive some of my routes from the server as a JSON object, but s ...

Obtain the current URL in a Node.js configuration file

In my application using the express framework, I have the following code in my app.js file: var express = require('express'); var app = module.exports = express(); var config = require('./config.js')(app, express); // Including ...

Supernumber Lottery: A Chance to Win Big!

I've been faced with the task of creating a random number generator for selecting lottery numbers. The challenge is to generate 6 unique numbers between 1 and 49, in ascending order, without any repeats. Additionally, there is a 7th number called the ...

Tips on adding background images to your chart's background

Is there a way to set an image as the background in Lightning Chart using chartXY.setChartBackground? ...