Loading an image to a >

后端 未结 6 839
闹比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:37

    As iEamin said in his answer, HTML 5 does now support this. The link he gave, http://www.html5rocks.com/en/tutorials/file/dndfiles/ , is excellent. Here is a minimal sample based on the samples at that site, but see that site for more thorough examples.

    Add an onchange event listener to your HTML:

    
    

    Make an image tag with an id (I'm specifying height=200 to make sure the image isn't too huge onscreen):

    
    

    Here is the JavaScript of the onchange event listener. It takes the File object that was passed as event.target.files[0], constructs a FileReader to read its contents, and sets up a new event listener to assign the resulting data: URL to the img tag:

    function onFileSelected(event) {
      var selectedFile = event.target.files[0];
      var reader = new FileReader();
    
      var imgtag = document.getElementById("myimage");
      imgtag.title = selectedFile.name;
    
      reader.onload = function(event) {
        imgtag.src = event.target.result;
      };
    
      reader.readAsDataURL(selectedFile);
    }
    

提交回复
热议问题