filereader 和 window.URL.createObjectURL

<template>
  <div class="file-preview">
    <h4>前端图片预览之 filereader 和 window.URL.createObjectURLh4>
    <div class="item">
      <p>1. filereader方式p>
      <input type="file" name="imgFile" id="imgFile" @change="inputChange">
      <div class="pvWrap">div>
    div>
    <div class="item">
      <p>2. window.URL.createObjectURLp>
      <input type="file" multiple name="imgFile2" id="imgFile2" @change="inputChange2">
      <div class="pvWrap2">div>
    div>
  div>
template>
<script>
export default {
  name: "FilePreview",
  data() {
    return {};
  },
  methods: {
    inputChange(e) {
      let ele = document.getElementById("imgFile").files[0];
      let fr = new FileReader();
      fr.onload = function(ele) {
        var pvImg = new Image();
        pvImg.src = ele.target.result;
        pvImg.setAttribute("id", "previewImg");
        pvImg.style.width = "100%";
        pvImg.style.height = "100%";
        let pvWrap = document.querySelector(".pvWrap");
        pvWrap.innerHTML = "";
        pvWrap.appendChild(pvImg);
      };
      fr.readAsDataURL(ele);
    },
    inputChange2() {
      let ele = document.getElementById("imgFile2").files;
      let createObjectURL = function(blob) {
        return window[window.webkitURL ? "webkitURL" : "URL"]["createObjectURL"](blob);
      };
      for (let i = 0; i < ele.length; i++) {
        const element = ele[i];
        let newImgData = createObjectURL(element);
        let pvImg = new Image();
        pvImg.src = newImgData;
        pvImg.style.width = "100%";
        pvImg.style.height = "100%";
        let pvWrap2 = document.querySelector(".pvWrap2");
        pvWrap2.appendChild(pvImg);
      }
    }
  }
};
script>
<style scoped>
.pvWrap,
.pvWrap2 {
  width: 400px;
  height: 200px;
}
style>

 

转载于:https://www.cnblogs.com/samsara-yx/p/11058960.html

你可能感兴趣的:(前端,ViewUI)