What's the safest way to use FileReader with i

2019-05-28 19:37发布

I have a form that has file selector. <input type="file" ... Run the code snippet below to see what it does.

On Safari on iOS8 there is a known bug that means you cannot read file content with FileReader. This only happens on real hardware, the iOS simulator works fine.

On Chrome on iOS8 this code sometimes just completely crashes the browser.

I don't want to use agent sniffing to decide whether or not to attempt the function. Is there a better way to write this so that I can gracefully degrade to a simpler version?

document.getElementById('files').addEventListener('change', handleFileSelect, false);

function handleFileSelect(evt) {
    var fileList = evt.target.files;
  
    for (var i = 0; i < fileList.length; i++) {
        loadFile(fileList[i]);
    }
}

function loadFile(file) {
    var reader = new FileReader();
    reader.onload = function (evt) {
        document.getElementById('list').innerHTML += "file loaded: " + evt.target.result;
    };

    reader.readAsDataURL(file); // broken in iOS8 && Safari
}
<h2>Choose 1 or more files</h2>

<input type="file" id="files" name="files[]" multiple="multiple" />

<h2>Loaded files will appear below:</h2>
<div id="list"></div>

It appears SO code snippets don't work on iOS so if you want to run the code, I've copied it to jsbin here: http://jsbin.com/zuyeteheroga/3/edit?html,js,output

1条回答
Viruses.
2楼-- · 2019-05-28 20:02

I have been using the following to take a picture using the phone's camera and display it on the web page:

<input type="file" id="fileInput" accept="image/*" onchange="inputFileChanged();" />
<img alt="The Picture" src="Content/1.jpg" id="imgDisplay" />
<script type="text/javascript">

    function inputFileChanged() {
        //alert("Input File Changed");
        var files = document.getElementById("fileInput").files;

        if (window.FileReader) { //Check browser - does it support File Reader?
            //alert("reader OK");
            loadImageFile(files);
        }
        else {
            alert("File Reader not Supported");
        }
    }

    function loadImageFile(files) {
        if (files && files.length) {
            var reader = new FileReader();
            reader.onload = (function (theImageElement) {
                return function (e) {
                    //alert("reader loaded");
                    theImageElement.src = e.target.result;
                }
            })(document.getElementById("imgDisplay"));
            reader.onerror = function (e) {
                alert("error " + e.target.error.code);
            }
            reader.readAsDataURL(files[0]);
        } else {
            alert("no file");
        }
    }
</script>

On iPhone Safari iOS8, error code 4 (NOT_READABLE_ERR) is returned. This is a known bug (supposed to be resolved on next release).

No problems (so far) with Chrome on iPhone iOS8

查看更多
登录 后发表回答