HTML5 Object tag with base64 data content causes C

2019-02-19 03:03发布

问题:

I am using the HTML5 FileReader to read a local file. I then want to immediately display the file contents within the browser, prior to uploading to the server.

I read the file, and attempt to display it, as follows:

var reader = new FileReader();
    reader.onloadend = function () {
        _moleculefilestream = reader.result;
        _molecule.filename = filelist[0].name;
        var filetype = _molecule.filename.substring(_molecule.filename.length - 3);
        var html = '';
        if (filetype == 'jpg' || filetype == 'gif' || filetype == 'png' || filetype == 'tif' || filetype == 'bmp') {
            html += '<img src="' + reader.result + '" />';
        }
        else {
            html += '<object id="zzzxxx" data="' + reader.result + '"';
            if (filetype.toLowerCase() == 'pdf') {
                // For pdf docs, specify a height and width
                html += ' width="770" height="350"';
            }
            html += '>';
            html += '</object>';
        }
        alert('we get here fine');
        $('#molecule-docviewer').html(html);
        alert('we have crashed by this point');
        MarkMoleculeAsDirty();
    }
    reader.readAsDataURL(filelist[0]); 

When I upload a pdf up to around 1.5Mb in Chrome, it all works fine. When I try uploading at 1.5Mb or larger, Chrome (V15) crashes with an "aw snap" message. It displays the "we get here fine" message, but crashes on the following line.

Anyone got any bright ideas on how to fix or workaround? Thanks.

回答1:

You should highly consider using a blob URL instead of a data URL. You're not actually manipulating the bytes of the file, so there is no reason to read the entire file into memory, then add a 33% overhead of base64 encoding it as a data URL.

window.URL = window.URL || window.webkitURL;

var file = filelist[0];
var url = window.URL.createObjectURL(file);
var html = '';
if (file.type && file.type.match('image/.*')) {
  html += '<img src="' + url + '" />';
}
....