【JavaScript小項目】在網頁上顯示選擇的圖片

  • 2020 年 2 月 13 日
  • 筆記

思路分析

  1. 選用<input type="file">原生組件,實現該組件美化。
  2. 選用<img src="file">實現圖片預覽。

代碼實現

<!DOCTYPE html>  <html>        <head>          <meta charset="UTF-8">          <title>圖片預覽</title>          <script src="js/test.js">              function upload(file) {                  console.log(file)                  let img = document.getElementById('img')                  let formData = new FormData()                  let temp = file.files[0]                  console.log(temp)                  if (temp){                      formData.append('file',temp)                      img.src = window.URL.createObjectURL(temp)                  }              }          </script>          <style type="text/css">              .myBtn{                  padding: 5px 10px;                  background: rgb(92,184,92);                  color: white;                  outline: none;                  border: none;                  border-radius: 5px;                  cursor: pointer;              }          </style>      </head>        <body>          <input type="file" style="display: none;" id="file" onchange="upload(this)" />          <button class="myBtn" onclick="fileBtn()">上傳文件</button>          <br />          <img src="" id="img" style="width: 50%">      </body>    </html>  

效果展示

本來是想部署通過網頁上傳一個圖片到服務器的功能的。

今天只實現了第一步,把圖片選擇和預覽做了。服務器端還要部署接受服務才行。

就這第一步都花費了兩個小時,孰能生巧啊。只學不習永遠都落實不了。


一番霧語:JavaScript上傳圖片並預覽。