gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:10:55 24 4
gpt4 key购买 nike

我正在尝试对本地文件进行 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-sitescripting 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 itwill paint it to the canvas (now it's just raw pixels) and finally itwill reencode it (it has nothing to do with your original fileanymore) check the dataURI strings... They're compeltely different andeven if you do the canvas operation from two different browsers,you'll have different outputs, while FileReader will always give youthe same output, since it encode the file directly, it doesn't decodeit.

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com