Force paste event to encode images in base64

后端 未结 1 657
难免孤独
难免孤独 2020-12-30 06:46

Background:

I\'m developing an HTML5 webapp for my company which is basically a Rich Text Editor (similar to Google Docs) that stores information in

相关标签:
1条回答
  • 2020-12-30 07:32

    Yes and no I believe.

    It is possible to intercept the paste event and fetch the pasted image as a file, then use FileReader to read the file as a Data URI (base 64 encoded PNG).

    However, Word seems to send a reference to a local file, which generates a security exception (at least on Chrome) because of a cross-domain request (http://... and file:///...). As far as I'm concerned there is no way to get the actual contents of such local files, and the contents are not sent as clipboard data itself.

    If you copy a "pure" image (e.g. out of Paint), you can get the base 64 encoded data as follows: http://jsfiddle.net/pimvdb/zTAuR/. Or append the image as a base 64 encoded PNG in the div: http://jsfiddle.net/pimvdb/zTAuR/2/.

    div.onpaste = function(e) {
        var data = e.clipboardData.items[0].getAsFile();
    
        var fr = new FileReader;
    
        fr.onloadend = function() {
            alert(fr.result.substring(0, 100)); // fr.result is all data
        };
    
        fr.readAsDataURL(data);
    };
    
    0 讨论(0)
提交回复
热议问题