使用input做簡單的上傳圖片


css 代碼:

.container{
      width: 200px;
      height: 200px;
      border: 1px solid #666;
    }

 

HTML 代碼:

<input type="file" id="photo">
<div class="container"></div>

 

JavaScript 代碼:

document.getElementById("photo").addEventListener("change",function(e){
      var files =this.files;
      var img = new Image();
      var reader =new FileReader();
      reader.readAsDataURL(files[0]);
      reader.onload =function(e){
        var dx =(e.total/1024)/1024;
        if(dx>=2){
          alert("文件大小大於2M");
          return;
        }
        img.src =this.result;
        img.style.width ="100%";
        img.style.height ="90%";
        document.querySelector('.container').appendChild(img);
      }
    })

 

FileReader 是html5提供讀取文件的api,作用是把文本流按指定格式讀取到緩存。

FileReader 有四種讀取文件的方式:

  readAsBinaryString、readAsDataURL、readAsText、readAsArrayBuffer;

基於預覽上傳后圖片的需求,需要將圖片讀取為DataURL。

 

點擊這里:自定義樣式上傳圖片

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM