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.