Loading an image to a >

后端 未结 6 852
闹比i
闹比i 2020-11-30 23:06

I\'m trying to load an image selected by the user through an element.

I added a onchange event handler to the input element like this:



        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 23:31

    In browsers supporting the File API, you can use the FileReader constructor to read files once they have been selected by the user.

    Example

    document.getElementById('picField').onchange = function (evt) {
        var tgt = evt.target || window.event.srcElement,
            files = tgt.files;
    
        // FileReader support
        if (FileReader && files && files.length) {
            var fr = new FileReader();
            fr.onload = function () {
                document.getElementById(outImage).src = fr.result;
            }
            fr.readAsDataURL(files[0]);
        }
    
        // Not supported
        else {
            // fallback -- perhaps submit the input to an iframe and temporarily store
            // them on the server until the user's session ends.
        }
    }
    

    Browser support

    • IE 10
    • Safari 6.0.2
    • Chrome 7
    • Firefox 3.6
    • Opera 12.02

    Where the File API is unsupported, you cannot (in most security conscious browsers) get the full path of a file from a file input box, nor can you access the data. The only viable solution would be to submit the form to a hidden iframe and have the file pre-uploaded to the server. Then, when that request completes you could set the src of the image to the location of the uploaded file.

提交回复
热议问题