4

I am try to make an upload picture webpage in mobile phones, but it always run out of memory and the browser quit once the picture is too big. Here are my code:

<input type="file" id="testFile" />
<img src="" style="position:relative;" id="uploadingImg" />

function setImage() {
    var fileList   = this.files;
    var imageType  = /image/;
    for(var i = 0;i < fileList.length;i++) {
        document.getElementById('uploadingImg').file = fileList[i];
        var reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('uploadingImg').src = e.target.result;
        }
        reader.readAsDataURL(fileList[i]);
    }
}



document.getElementById('testFile').addEventListener('change', setImage, false);

Does anyone knows how to preview one picture by using <img> or <canvas> element? Please don't use "readAsDataURL", because when it comes to document.getElementById('uploadingImg').src = e.target.result; It will run out of memory. Because the base64 Url occupy too much memory and it exist in the memory with many three or four copies.

How can I use "readAsArrayBuffer" and use "drawImage" by canvas? or other method?

All is ok if I can preview one picture in local disk without using "readAsDataUrl".

Thanks!

Varun Sridharan
  • 1,917
  • 2
  • 19
  • 52
  • 1
    Try out this thread http://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded – mattnull Aug 11 '12 at 23:33

1 Answers1

5

In most browsers you don't need to use FileReader (and consequently readAsDataUrl) for this. Instead, you can use the File API's createObjectURL method. Here's your setImage() function rewritten:

function setImage() {
    var file = this.files[0];
    var URL = window.URL || window.webkitURL;
    if (URL.createObjectURL && (file.type == "image/jpeg" || file.type == "image/png" || file.type == "image/gif")) {
        document.getElementById('uploadingImg').src = URL.createObjectURL(file);
    } else {
        alert('Unable to show preview');
    }
}

Browser support is still a bit patchy, though, so check support tables such as caniuse.com before deciding whether to use it: http://caniuse.com/#search=createobjectURL

tagawa
  • 4,184
  • 1
  • 24
  • 34
  • 2
    Remember to revokeObjectUrl when you're done with it to avoid potential memory leaks. – Isius Dec 13 '13 at 07:19