上传时如何在文本预览中添加文本区域

时间:2018-10-17 11:45:14

标签: javascript jquery html css xmlhttprequest

我整整3天一直在努力解决这个问题。任何帮助将不胜感激!

我有一个“添加我的照片”按钮,单击该按钮后,会弹出一个窗口,可以选择上传图片或更多图片。因此,当我单击“选择文件”按钮或拖放图片或更多图片时,它将在右侧预览图片。

我需要帮助的是:当我上传一张照片或2张照片时,我希望在每张照片的右侧显示一个文本区域,用户可以在其中写一些东西(例如标题)。另外,在显示图片和捕获的图像后,我需要选择删除其中一个或全部的选项。这是一张图片:

enter image description here

这是CodePen代码:https://codepen.io/anon/pen/VEQMwm

预先感谢您的帮助。

此外,这是代码:

// ---------- THIS IS FOR THE POPUP ---------- //
  function CustomAlert() {
     this.performCustomAlert = function (dialog) {
        var windowWidth = window.innerWidth;
        var windowHeight = window.innerHeight;
        var dialogoverlay = document.getElementById('dialogoverlay');
        var dialogbox = document.getElementById('dialogbox');
        dialogoverlay.style.display = "block";
        dialogoverlay.style.height = windowHeight + "px";
        dialogbox.style.display = "block";
     }
     this.ok = function () {
        document.getElementById('dialogbox').style.display = "none";
        document.getElementById('dialogoverlay').style.display = "none";
     }
  }

  var newAlert = new CustomAlert();

  // ------------- TABS ----------------- //
  function openTab(evt, tabName) {
      var i, tabcontent, tablinks;
      tabcontent = document.getElementsByClassName("tabcontent");
      for (i = 0; i < tabcontent.length; i++) {
          tabcontent[i].style.display = "none";
      }
      tablinks = document.getElementsByClassName("tablinks");
      for (i = 0; i < tablinks.length; i++) {
          tablinks[i].className = tablinks[i].className.replace(" active", "");
      }
      document.getElementById(tabName).style.display = "block";
      evt.currentTarget.className += " active";
  }

  document.getElementById("defaultOpen").click();

  // ---------------- UPLOAD --------------------------//
  // ************************ Drag and drop ***************** //
  let dropArea = document.getElementById("drop-area")

  // Prevent default drag behaviors
  ;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    dropArea.addEventListener(eventName, preventDefaults, false)   
    document.body.addEventListener(eventName, preventDefaults, false)
  })

  // Highlight drop area when item is dragged over it
  ;['dragenter', 'dragover'].forEach(eventName => {
    dropArea.addEventListener(eventName, highlight, false)
  })

  ;['dragleave', 'drop'].forEach(eventName => {
    dropArea.addEventListener(eventName, unhighlight, false)
  })

  // Handle dropped files
  dropArea.addEventListener('drop', handleDrop, false)

  function preventDefaults (e) {
    e.preventDefault()
    e.stopPropagation()
  }

  function highlight(e) {
    dropArea.classList.add('highlight')
  }

  function unhighlight(e) {
    dropArea.classList.remove('active')
  }

  function handleDrop(e) {
    var dt = e.dataTransfer
    var files = dt.files

    handleFiles(files)
  }

  let uploadProgress = []
  let progressBar = document.getElementById('progress-bar')

  function initializeProgress(numFiles) {
    progressBar.value = 0
    uploadProgress = []

    for(let i = numFiles; i > 0; i--) {
      uploadProgress.push(0)
    }
  }

  function updateProgress(fileNumber, percent) {
    uploadProgress[fileNumber] = percent
    let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
    console.debug('update', fileNumber, percent, total)
    progressBar.value = total
  }

  function handleFiles(files) {
    files = [...files]
    initializeProgress(files.length)
    files.forEach(uploadFile)
    files.forEach(previewFile)
  }

  function previewFile(file) {
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onloadend = function() {
      let img = document.createElement('img')
      img.src = reader.result
      document.getElementById('gallery').appendChild(img)
    }
  }

  function uploadFile(file, i) {
    var xhr = new XMLHttpRequest()
    var formData = new FormData()
    xhr.open('POST', true)
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

    // Update progress (can be used to show progress indicator)
    xhr.upload.addEventListener("progress", function(e) {
      updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
    })

    xhr.addEventListener('readystatechange', function(e) {
      if (xhr.readyState == 4 && xhr.status == 200) {
        updateProgress(i, 100) // <- Add this
      }
      else if (xhr.readyState == 4 && xhr.status != 200) {
        // Error. Inform the user
      }
    })

    formData.append('upload_preset', 'ujpu6gyk')
    formData.append('file', file)
    xhr.send(formData)
  }
.add-photo{
    width: 18%;
    background-color: #00a100;
    color: #fff;
    padding: 11px 13px;
    border: 3px solid #00a100;
    -webkit-transition: 0.3s ease;
    transition: 0.3s ease;
    cursor: pointer;
    text-align: center;
    font-size: 13px;
    font-weight: 550;
    border-radius: 1px;
    margin-left: 41%;
  }

  * {
      box-sizing: border-box;
  }

  #dialogoverlay {
    display: none;
    opacity: 0.5;
    /*so that user can see through it*/
    position: fixed;
    top: 0px;
    left: 0px;
    background: black;
    z-index: 10;
    height: 100%;
    width: 100%;
  }

  #dialogbox {
    display: none;
    position: fixed;
    background: #ffffff;
    border-radius: 1px;
    border: 0.5px solid #ccc;
    z-index: 10;
    left: 25%;
    top: 20%;
    width: 50%;
    height: 400px;
    -webkit-animation: fadeEffect 0.3s;
    animation: fadeEffect 0.3s;
  }

  #close-popup {
    float: right;
    background-color: red;
    color: #474747;
    font-size: 15px;
  }

  .header{
    position: absolute;
    width: 100.2%;
    background-color: white;
    height: 11%;
    top: 5.4%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .content-centre{
    width: 99%;
    height: 77%;
    margin-left: 3px;
    margin-top: 46px; 
  }

  #content-leftside{
    width: 65%;
    height: 100%;
    float: left;
  }

  .tab {
    overflow: hidden;
  }

  .tab button {
    width: 33.3%;
    height: 14%;
    background-color: #acacac;
    float: left;
    color: white;
    outline: none;
    cursor: pointer;
    padding: 6px;
    transition: 0.3s;
    border-right: 1px solid #fff;
  }

  .tab button:hover {
    background-color: #474747;
  }

  .tab button.active {
    background-color: #474747;
  }

  .tabcontent {
    display: none;
    padding: 6px 12px;
  }

  #content-rightside{
    width: 35%;
    height: 100%;
    float: right;
    background-color: #ffffff;
    border-left: 1px solid #dddddd;
  }

  #right-topbar{
    width: 100%;
    height: 9%;
    background-color: #474747;
    color: #fff;
    padding: 5px;
    text-align: center;
    transition: 0.3s;
  }

  .footer{
    position: absolute;
    width: 100.2%;
    background-color: #474747;
    height: 11%;
    bottom: -5.6%;
    left: 50%;
    /* top: calc(50% - 50px); */
    transform: translate(-50%, -50%);
  }


  /*------------------- UPLOAD AREA -----------------------*/

  #drop-area {
    border: 2px dashed #ccc;
    border-radius: 8px;
    width: 98%;
    margin: 24px auto;
    padding: 15px;
  }

  #progress-bar{
    display: none;
  }

  #gallery {
    margin-top: 5%;
  }

  #gallery img {
    width: 55px;
    height: 50px;
    margin-bottom: 10px;
    margin-left: 10px
  }

  .button {
    display: inline-block;
    padding: 10px;
    background: #00a100;
    color: #fff;
    cursor: pointer;
    border-radius: 5px;
  }

  #fileElem {
    display: none;
  }

  #upload-button{
    font-size: 40px;
    color: #00a100;
<button class="add-photo" onclick="newAlert.performCustomAlert()">ADD MY PHOTO</button> 
    <div class="popup-upload">
      <div id="dialogoverlay"></div>
      <!--------------- SELECT MEDIA BOX ---------------->
      <div id="dialogbox">
        <!--------------- HEADER OF THE BOX ---------------->
        <div class="header">
          <!--------------- CLOSE POPUP ---------------->
          <button id="close-popup" onclick="newAlert.ok()"><i class="fa fa-times" style="margin-top: 8px; margin-right: 7px;"></i></button>
          <div class="select-media">
              <i class="fa fa-camera" id="select-camera"></i>
              <h2 id="select-media">SELECT YOUR MEDIA</h2>
          </div>
        </div>

        <!--------------- CONTENT OF THE BOX ---------------->
        <div class="content-centre">
          <!--------------- LEFT CONTENT ---------------->
          <div id="content-leftside">
            <div class="tab">
              <button class="tablinks" id="defaultOpen" onclick="openTab(event, 'Desktop')"><span class="fa fa-desktop"></span>&nbsp; Desktop</button>
              <button class="tablinks" onclick="openTab(event, 'Facebook')"><span class="fa fa-facebook"></span>&nbsp; Facebook</button>
              <button class="tablinks" onclick="openTab(event, 'Instagram')"><span class="fa fa-instagram"></span>&nbsp; Instagram</button>
            </div>

            <div id="Desktop" class="tabcontent">
              <div id="drop-area">
                <form class="my-form">
                  <span class="fa fa-cloud-upload" id="upload-button"></span>
                  <p id="drag-text">Drag & Drop Your <br> Photos or Videos <br> To Upload</p>
                  <input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
                  <label class="button" for="fileElem">or Select Files</label>
                </form>
              </div>
            </div>

            <div id="Facebook" class="tabcontent">
              <h3>Facebook</h3>
            </div>

            <div id="Instagram" class="tabcontent">
              <h3>Instagram</h3>
            </div>
          </div>
          <!--------------- RIGHT CONTENT ---------------->
          <div id="content-rightside">
            <!--------------- RIGHT TOPBAR ---------------->
            <div id="right-topbar">
              <h1>Selected Media</h1>
            </div>
            <progress id="progress-bar" max=100 value=0></progress>
            <div id="gallery"/></div>
          </div>
        </div>
        <div class="footer">
        </div>
      </div>
    </div>
  </div>

2 个答案:

答案 0 :(得分:-1)

查看下面的代码,我对PreviewFile()函数进行了一些更改。 我希望,通过查看下面的代码,您可以了解想法。

// ---------- THIS IS FOR THE POPUP ---------- //
function CustomAlert() {
  this.performCustomAlert = function(dialog) {
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    var dialogoverlay = document.getElementById('dialogoverlay');
    var dialogbox = document.getElementById('dialogbox');
    dialogoverlay.style.display = "block";
    dialogoverlay.style.height = windowHeight + "px";
    dialogbox.style.display = "block";
  }
  this.ok = function() {
    document.getElementById('dialogbox').style.display = "none";
    document.getElementById('dialogoverlay').style.display = "none";
  }
}

var newAlert = new CustomAlert();

// ------------- TABS ----------------- //
function openTab(evt, tabName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.className += " active";
}

document.getElementById("defaultOpen").click();

// ---------------- UPLOAD --------------------------//
// ************************ Drag and drop ***************** //
let dropArea = document.getElementById("drop-area")

// Prevent default drag behaviors
;
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
  dropArea.addEventListener(eventName, preventDefaults, false)
  document.body.addEventListener(eventName, preventDefaults, false)
})

// Highlight drop area when item is dragged over it
;
['dragenter', 'dragover'].forEach(eventName => {
  dropArea.addEventListener(eventName, highlight, false)
})

;
['dragleave', 'drop'].forEach(eventName => {
  dropArea.addEventListener(eventName, unhighlight, false)
})

// Handle dropped files
dropArea.addEventListener('drop', handleDrop, false)

function preventDefaults(e) {
  e.preventDefault()
  e.stopPropagation()
}

function highlight(e) {
  dropArea.classList.add('highlight')
}

function unhighlight(e) {
  dropArea.classList.remove('active')
}

function handleDrop(e) {
  var dt = e.dataTransfer
  var files = dt.files

  handleFiles(files)
}

let uploadProgress = []
let progressBar = document.getElementById('progress-bar')

function initializeProgress(numFiles) {
  progressBar.value = 0
  uploadProgress = []

  for (let i = numFiles; i > 0; i--) {
    uploadProgress.push(0)
  }
}

function updateProgress(fileNumber, percent) {
  uploadProgress[fileNumber] = percent
  let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
  console.debug('update', fileNumber, percent, total)
  progressBar.value = total
}

function handleFiles(files) {
  files = [...files]
  initializeProgress(files.length)
  files.forEach(uploadFile)
  files.forEach(previewFile)
}

function previewFile(file) {
  let reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onloadend = function() {
    let img = document.createElement('img')
    img.src = reader.result

    var mainDiv = document.createElement("div")
    mainDiv.className = "box"
    mainDiv.appendChild(img)

    var textbx = document.createElement("textarea")
    textbx.placeholder ="Caption..."
    mainDiv.appendChild(textbx)

    var btn = document.createElement("button")
    var tx = document.createTextNode("X");
    btn.onclick = function() {
      $(this).closest(".box").remove()
    }
    btn.appendChild(tx);
    mainDiv.appendChild(btn)

    document.getElementById('gallery').appendChild(mainDiv)

  }
}

function uploadFile(file, i) {
  var xhr = new XMLHttpRequest()
  var formData = new FormData()
  xhr.open('POST', true)
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

  // Update progress (can be used to show progress indicator)
  xhr.upload.addEventListener("progress", function(e) {
    updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
  })

  xhr.addEventListener('readystatechange', function(e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      updateProgress(i, 100) // <- Add this
    } else if (xhr.readyState == 4 && xhr.status != 200) {
      // Error. Inform the user
    }
  })

  formData.append('upload_preset', 'ujpu6gyk')
  formData.append('file', file)
  xhr.send(formData)
}
  .add-photo {
  width: 18%;
  background-color: #00a100;
  color: #fff;
  padding: 11px 13px;
  border: 3px solid #00a100;
  -webkit-transition: 0.3s ease;
  transition: 0.3s ease;
  cursor: pointer;
  text-align: center;
  font-size: 13px;
  font-weight: 550;
  border-radius: 1px;
  margin-left: 41%;
}

* {
  box-sizing: border-box;
}

#dialogoverlay {
  display: none;
  opacity: 0.5;
  /*so that user can see through it*/
  position: fixed;
  top: 0px;
  left: 0px;
  background: black;
  z-index: 10;
  height: 100%;
  width: 100%;
}

#dialogbox {
  display: none;
  position: fixed;
  background: #ffffff;
  border-radius: 1px;
  border: 0.5px solid #ccc;
  z-index: 10;
  left: 25%;
  top: 20%;
  width: 50%;
  height: 400px;
  -webkit-animation: fadeEffect 0.3s;
  animation: fadeEffect 0.3s;
}

#close-popup {
  float: right;
  background-color: red;
  color: #474747;
  font-size: 15px;
}

.header {
  position: absolute;
  width: 100.2%;
  background-color: white;
  height: 11%;
  top: 5.4%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.content-centre {
  width: 99%;
  height: 77%;
  margin-left: 3px;
  margin-top: 46px;
}

#content-leftside {
  width: 65%;
  height: 100%;
  float: left;
}

.tab {
  overflow: hidden;
}

.tab button {
  width: 33.3%;
  height: 14%;
  background-color: #acacac;
  float: left;
  color: white;
  outline: none;
  cursor: pointer;
  padding: 6px;
  transition: 0.3s;
  border-right: 1px solid #fff;
}

.tab button:hover {
  background-color: #474747;
}

.tab button.active {
  background-color: #474747;
}

.tabcontent {
  display: none;
  padding: 6px 12px;
}

#content-rightside {
  width: 35%;
  height: 100%;
  float: right;
  background-color: #ffffff;
  border-left: 1px solid #dddddd;
}

#right-topbar {
  width: 100%;
  height: 9%;
  background-color: #474747;
  color: #fff;
  padding: 5px;
  text-align: center;
  transition: 0.3s;
}

.footer {
  position: absolute;
  width: 100.2%;
  background-color: #474747;
  height: 11%;
  bottom: -5.6%;
  left: 50%;
  /* top: calc(50% - 50px); */
  transform: translate(-50%, -50%);
}


/*------------------- UPLOAD AREA -----------------------*/

#drop-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  width: 98%;
  margin: 24px auto;
  padding: 15px;
}

#progress-bar {
  display: none;
}

#gallery {
  margin-top: 5%;
}

#gallery img {
  width: 55px;
  height: 50px;
  margin-bottom: 10px;
  margin-left: 10px
}

.button {
  display: inline-block;
  padding: 10px;
  background: #00a100;
  color: #fff;
  cursor: pointer;
  border-radius: 5px;
}

#fileElem {
  display: none;
}

#upload-button {
  font-size: 40px;
  color: #00a100;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add-photo" onclick="newAlert.performCustomAlert()">ADD MY PHOTO</button>
<div class="popup-upload">
  <div id="dialogoverlay"></div>
  <!--------------- SELECT MEDIA BOX ---------------->
  <div id="dialogbox">
    <!--------------- HEADER OF THE BOX ---------------->
    <div class="header">
      <!--------------- CLOSE POPUP ---------------->
      <button id="close-popup" onclick="newAlert.ok()"><i class="fa fa-times" style="margin-top: 8px; margin-right: 7px;"></i></button>
      <div class="select-media">
        <i class="fa fa-camera" id="select-camera"></i>
        <h2 id="select-media">SELECT YOUR MEDIA</h2>
      </div>
    </div>

    <!--------------- CONTENT OF THE BOX ---------------->
    <div class="content-centre">
      <!--------------- LEFT CONTENT ---------------->
      <div id="content-leftside">
        <div class="tab">
          <button class="tablinks" id="defaultOpen" onclick="openTab(event, 'Desktop')"><span class="fa fa-desktop"></span>&nbsp; Desktop</button>
          <button class="tablinks" onclick="openTab(event, 'Facebook')"><span class="fa fa-facebook"></span>&nbsp; Facebook</button>
          <button class="tablinks" onclick="openTab(event, 'Instagram')"><span class="fa fa-instagram"></span>&nbsp; Instagram</button>
        </div>

        <div id="Desktop" class="tabcontent">
          <div id="drop-area">
            <form class="my-form">
              <span class="fa fa-cloud-upload" id="upload-button"></span>
              <p id="drag-text">Drag & Drop Your <br> Photos or Videos <br> To Upload</p>
              <input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
              <label class="button" for="fileElem">or Select Files</label>
            </form>
          </div>
        </div>

        <div id="Facebook" class="tabcontent">
          <h3>Facebook</h3>
        </div>

        <div id="Instagram" class="tabcontent">
          <h3>Instagram</h3>
        </div>
      </div>
      <!--------------- RIGHT CONTENT ---------------->
      <div id="content-rightside">
        <!--------------- RIGHT TOPBAR ---------------->
        <div id="right-topbar">
          <h1>Selected Media</h1>
        </div>
        <progress id="progress-bar" max=100 value=0></progress>
        <div id="gallery" /></div>
    </div>
  </div>
  <div class="footer">
  </div>
</div>
</div>
</div>

答案 1 :(得分:-1)

只需用此替换PreviewFile函数。

  function previewFile(file) {
    let reader = new FileReader()
    reader.readAsDataURL(file);
    reader.onloadend = function() {
     var gallleryDiv=document.getElementById('gallery');
     var wrapperDiv = document.createElement("div");
     let img = document.createElement('img');
     img.src = reader.result;
     wrapperDiv.className = "wrapperDiv";
     wrapperDiv.appendChild(img)
     var textbx = document.createElement("textarea");
     wrapperDiv.appendChild(textbx);
     var btn = document.createElement("button");
     var tx = document.createTextNode("X");
     btn.onclick = function() {$(this).closest(".wrapperDiv").remove()}
     btn.appendChild(tx);
     wrapperDiv.appendChild(btn);
     gallleryDiv.appendChild(wrapperDiv);
    }
  }