简体   繁体   中英

JS: how can I base64 encode a local file without XMLHttpRequest?

I'm trying to base64 encode a local file. It's next to my .js file so there's no uploading going on. Solutions like this (using XMLHttpRequest ) get a cross-site scripting error.

I'm trying something like this (which doesn't work but it might help explain my problem):

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);

Anyone have any experience doing this locally?

Solutions like this (using XMLHttpRequest) get a cross-site scripting error.

If using chrome or chromium browser, you could launch with --allow-file-access-from-files flag set to allow request of resource from local filesystem using XMLHttpRequest() or canvas.toDataURL() .

You can use <img> element, <canvas> element .toDataURL() to create data URL of local image file without using 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); // set image `type` to `image/jpeg`
  console.log(res);
}
img.src = file;

You could alternatively use XMLHttpRequest() as described at Convert local image to base64 string in Javascript .

See also How to print all the txt files inside a folder using java script .


For a details of difference of returned data URI from either approach see canvas2d toDataURL() different output on different browser

As described by @Kaiido at comment below

it will first decode it, at this stage it's still your file, then it will paint it to the canvas (now it's just raw pixels) and finally it will reencode it (it has nothing to do with your original file anymore) check the dataURI strings... They're compeltely different and even if you do the canvas operation from two different browsers, you'll have different outputs, while FileReader will always give you the same output, since it encode the file directly, it doesn't decode it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM