我正在尝试对本地文件进行 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/