<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>WebCat</title>
    <style>
      #preview{
        max-width:80%;
      }
    </style>
  </head>
  <body>    
    <input type="file" />
    <img src="" id="preview" alt=""/>
    <script>
    function BASE64(file){
        return new Promise((resolve, reject) => {
          var reader = new FileReader();
          reader.onload = (e) =>{
            resolve(e.target.result);
          }
          reader.readAsDataURL(file);
        });
      }
      var inp = document.querySelector("input");
      inp.onchange = async function(){
        preview.src = await BASE64(inp.files[0]);
      }
    </script>
  </body>
</html>
<p>要实现此功能,您可以将 BASE64 函数改为返回一个 Promise,并在 onload 事件中 resolve 该 Promise。然后,您可以使用 async/await 来等待 BASE64 函数完成,并将返回的结果设置为 preview 的 src 属性。以下是修改后的代码:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot; name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no&quot;&gt;
    &lt;title&gt;WebCat&lt;/title&gt;
    &lt;style&gt;
      #preview{
        max-width:80%;
      }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;    
    &lt;input type=&quot;file&quot; /&gt;
    &lt;img src=&quot;&quot; id=&quot;preview&quot; alt=&quot;&quot;/&gt;
    &lt;script&gt;
    function BASE64(file){
        return new Promise((resolve, reject) =&gt; {
          var reader = new FileReader();
          reader.onload = (e) =&gt;{
            resolve(e.target.result);
          }
          reader.readAsDataURL(file);
        });
      }
      var inp = document.querySelector(&quot;input&quot;);
      inp.onchange = async function(){
        preview.src = await BASE64(inp.files[0]);
      }
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>这样,当您选择文件后,将会将文件的 BASE64 编码设置为 preview 的 src 属性,实现了该功能。</p>
使用 JavaScript 将文件转换为 Base64 并显示预览图像

原文地址: https://www.cveoy.top/t/topic/qeZm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录