亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

上傳前顯示圖像預覽

上傳前顯示圖像預覽

素胚勾勒不出你 2019-07-16 18:19:43
上傳前顯示圖像預覽在我的HTML表單中,我使用類型文件進行輸入,例如: <input type="file" multiple>然后單擊輸入按鈕選擇多個文件?,F在我想在提交表單之前顯示選定圖像的預覽。如何在HTML 5中做到這一點?
查看完整描述

3 回答

?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

HTML 5附帶文件API規范,這允許您創建允許用戶在本地與文件交互的應用程序;這意味著您可以加載文件并在瀏覽器中呈現它們,而無需實際上傳文件。文件API的一部分是文件閱讀器接口,它允許web應用程序異步讀取文件的內容。

下面是一個使用FileReader類將圖像讀取為DataURL,并通過設置src圖像標記到數據URL的屬性:

html代碼:

<input type="file" id="files" /><img id="image" />

JavaScript代碼:

document.getElementById("files").onchange = function () {
    var reader = new FileReader();

    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("image").src = e.target.result;
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);};

這是一篇關于在JavaScript中使用文件API.

下面的HTML示例中的代碼片段過濾掉用戶選擇的圖像,并將選定的文件呈現為多個縮略圖預覽:

function handleFileSelect(evt) {
    var files = evt.target.files;

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = 
          [
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', 
            e.target.result,
            '" title="', escape(theFile.name), 
            '"/>'
          ].join('');
          
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple /><output id="list"></output>


查看完整回答
反對 回復 2019-07-16
  • 3 回答
  • 0 關注
  • 449 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號