上傳圖片,預覽並保存成blob類型 和 base64


場景: 獲取到一個file類型的圖片,如果直接在html中預覽?這里就是利用html5的新特性,將圖片轉換為Base64的形式顯示出來。有兩種方法:

方法一:利用URL.createObjectURL()

<!DOCTYPE html>
<html>
  <head>
    <title>base</title>
  </head>
<body>
  <input type="file" name="" id="file">
  <img src="" id="img">
<script type="text/javascript">
window.onload = function () {
  let $img = document.getElementById('img')
    file.onchange = function (e) {
      console.log(e.target.files[0])
      let file = e.target.files[0]
      let fileUrl = window.URL.createObjectURL(file)
      $img.src = fileUrl
      img.onload = function () {
      // 手動回收
      URL.revokeObjectURL(fileUrl)
      }
    }
  }
</script>
</body>
</html>

當選擇圖片后,生成的img src類似"blob:null/4304d4f3-c13b-43e8-83f6-8c80426520ff",能正常顯示圖片。

方法二: 利用FileReader.readAsDataURL()

<!DOCTYPE html>
<html>
   <head>
      <title>base</title>
   </head>
<body>
    <input type="file" name="" id="file">
    <img src="" id="img">
<script type="text/javascript">
window.onload = function () {
  let $img = document.getElementById('img')
    file.onchange = function (e) {
      console.log(e.target.files[0])
      let file = e.target.files[0]
      const fr = new FileReader(file)
      fr.readAsDataURL(file)
      fr.onload = function () {
      $img.src = this.result
    }
  }
}
</script>
</body>
</html>

img標簽的src將會是像這樣:"data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABkCAYAAADDhn8LAAA==,能夠正常顯示。

 

原文鏈接:https://juejin.im/post/5b5187da51882519ec07fa41


免責聲明!

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



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