且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 JavaScript 中将 Blob 对象转换为 base64

更新时间:2021-10-29 22:03:17

Nick Retallack 在本页的回答 剪贴板功能中的粘贴图像如何在 Gmail 和 Google Chrome 12+ 中工作? 完全符合我的要求.

Nick Retallack's answer at this page How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+? does exactly what I want.

所以新的代码是:

var items = e.clipboardData.items;
if (items) {
// Loop through all items, looking for any kind of image
    for (var i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") !== -1) {
            // We need to represent the image as a file,
            var blob = items[i].getAsFile();

            var reader = new FileReader();
                reader.onload = function(event){
                    createImage(event.target.result); //event.target.results contains the base64 code to create the image.
                };
                reader.readAsDataURL(blob);//Convert the blob from clipboard to base64
            }
        }
    }