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

标签 javascript

我正在尝试对本地文件进行 Base64 编码。它位于我的 .js 文件旁边,因此不会进行上传。解决方案如 this (使用 XMLHttpRequest)出现跨站点脚本错误。

我正在尝试这样的事情(这不起作用,但它可能有助于解释我的问题):

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

有人有在本地执行此操作的经验吗?

最佳答案

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

如果使用 chrome 或 chromium 浏览器,您可以使用 --allow-file-access-from-files 启动设置标志以允许使用 XMLHttpRequest() 从本地文件系统请求资源或canvas.toDataURL() .

您可以使用<img>元素,<canvas>元素.toDataURL()创建data URL不使用 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;

您也可以使用XMLHttpRequest()Convert local image to base64 string in Javascript 中所述.

另请参阅How to print all the txt files inside a folder using java script .


返回的差异详情data URI无论哪种方法,请参见 canvas2d toDataURL() different output on different browser

正如 @Kaiido 在 comment 所描述的那样下面

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.

关于javascript - JS : how can I base64 encode a local file without XMLHttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887005/

相关文章:

javascript - IE 11.0.10 无法显示使用 Javascript 更新的 HTML,除非打开控制台

c# - 使用 Jquery 动态查找中继器中的控件

javascript - 使用 svg.js 加载、转换和嵌入 SVG 文件

javascript - 逐步增强表格(提交)

javascript - keydown 上普通字符和半字符的区别

javascript - JavaScript 剪刀石头布游戏的游戏计数器无法正常工作

javascript - 使用 JavaScript 将类添加到 'body'

javascript - 如何将 SAFEARRAY(字节数组)放入 HTML 隐藏字段

javascript - emberjs 嵌套 {{#each}} 不起作用

javascript - 服务不会以 Angular 方式将数据返回到 Controller