使用jQuery进行图像预览

时间:2016-01-11 06:29:27

标签: javascript jquery

我尝试用jQuery做多个输入图像预览。预览图像工作正常,但同一div中的图像预览,我需要在不同的div中的每个图像预览。我该怎么办?

HTML

<html>
   <form action="index.php" id="myForm" name="myForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
     desktop:<input type="file" id="files" name="files" multiple><br/>
          <div id="selectedFiles"></div>
      mobile:<input type="file" id="mobile" name="mobile" multiple><br/>
          <div id="selectFiles"></div>
     <button type="submit">Submit</button>
     </form></br></body>
</html>

custom.js

$(document).ready(function() {
/*multiple image preview first input*/

    $("#files").on("change", handleFileSelect);

   selDiv = $("#selectedFiles");
   $("#myForm").on("submit", handleForm);

   $("body").on("click", ".selFile", removeFile);

   /*end image preview */

   /* Multiple image preview second input*/
   $("#mobile").on("change", handleFileSelect);

   selDivM = $("#selectFiles");
   $("#myForm").on("submit", handleForm);

   $("body").on("click", ".selFile", removeFile);

  /*end image preview*/
)}

方法
处理文件选择功能

var selDiv = "";
var selDivM="";
var storedFiles = [];

function handleFileSelect(e) {
   var files = e.target.files;
   var filesArr = Array.prototype.slice.call(files);
   filesArr.forEach(function(f) {

    if(!f.type.match("image.*")) {
        return;
    }
    storedFiles.push(f);

    var reader = new FileReader();
    reader.onload = function (e) {
     var html = "<div><img src=\"" + e.target.result + "\"       data-file='"+f.name+"' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
        if ( typeof selDivM !== "") {
            selDivM.append(html);
        }else {
            selDiv.append(html);
        }

    }
    reader.readAsDataURL(f);
});

}

处理表格的功能

function handleForm(e) {
e.preventDefault();
var data = new FormData();

for(var i=0, len=storedFiles.length; i<len; i++) {
    data.append('files', storedFiles[i]);
}

var xhr = new XMLHttpRequest();
xhr.open('POST', 'handler.cfm', true);

xhr.onload = function(e) {
    if(this.status == 200) {
        console.log(e.currentTarget.responseText);
        alert(e.currentTarget.responseText + ' items uploaded.');
    }
}

xhr.send(data);
}

单击执行删除文件的功能

function removeFile(e) {
   var file = $(this).data("file");
   for(var i=0;i<storedFiles.length;i++) {
    if(storedFiles[i].name === file) {
        storedFiles.splice(i,1);
        break;
    }
}
$(this).parent().remove();
}

see code pen snippet

$(document).ready(function() {
    /*multiple image preview first input*/

    $("#files").on("change", handleFileSelect);

    selDiv = $("#selectedFiles");
    $("#myForm").on("submit", handleForm);

    $("body").on("click", ".selFile", removeFile);

    /*end image preview */

    /* Multiple image preview second input*/
    $("#mobile").on("change", handleFileSelect);

    selDivM = $("#selectFiles");
    $("#myForm").on("submit", handleForm);

    $("body").on("click", ".selFile", removeFile);
 });
    /*multiple image preview*/


var selDiv = "";
// var selDivM="";
var storedFiles = [];

function handleFileSelect(e) {
    var files = e.target.files;
    var filesArr = Array.prototype.slice.call(files);
    filesArr.forEach(function(f) {

        if(!f.type.match("image.*")) {
            return;
        }
        storedFiles.push(f);

        var reader = new FileReader();
        reader.onload = function (e) {
            var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
             selDivM.append(html);
          }
        reader.readAsDataURL(f);
    });

}

function handleForm(e) {
    e.preventDefault();
    var data = new FormData();

    for(var i=0, len=storedFiles.length; i<len; i++) {
        data.append('files', storedFiles[i]);
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'handler.cfm', true);

    xhr.onload = function(e) {
        if(this.status == 200) {
            console.log(e.currentTarget.responseText);
            alert(e.currentTarget.responseText + ' items uploaded.');
        }
    }

    xhr.send(data);
}

function removeFile(e) {
    var file = $(this).data("file");
    for(var i=0;i<storedFiles.length;i++) {
        if(storedFiles[i].name === file) {
            storedFiles.splice(i,1);
            break;
        }
    }
    $(this).parent().remove();
}
#selectedFiles img {
            max-width: 200px;
            max-height: 200px;
            float: left;
            margin-bottom:10px;
        }
        #userActions input{
            width: auto;
            margin: auto;
        }
        #selectFiles img {
            max-width: 200px;
            max-height: 200px;
            float: left;
            margin-bottom:10px;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
  <body>
   <form action="index.php" id="myForm" name="myForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
     desktop:<input type="file" id="files" name="files" multiple><br/>
          <div id="selectedFiles"></div>
      mobile:<input type="file" id="mobile" name="mobile" multiple><br/>
          <div id="selectFiles"></div>
     <button type="submit">Submit</button>
     </form>
  </body>
</html>

2 个答案:

答案 0 :(得分:4)

这是基于您的剪辑....根据设备类型创建预览div

$(document).ready(function() {
  /*multiple image preview first input*/

  $("#files").on("change", handleFileSelect);

  selDiv = $("#selectedFiles");
  $("#myForm").on("submit", handleForm);

  $("body").on("click", ".selFile", removeFile);

  /*end image preview */

  /* Multiple image preview second input*/
  $("#mobile").on("change", handleFileSelect);

  selDivM = $("#selectFilesM");
  $("#myForm").on("submit", handleForm);

  $("body").on("click", ".selFile", removeFile);

  console.log($("#selectFilesM").length);
});
/*multiple image preview*/


var selDiv = "";
// var selDivM="";
var storedFiles = [];

function handleFileSelect(e) {

  var files = e.target.files;
  var filesArr = Array.prototype.slice.call(files);
  var device = $(e.target).data("device");
  filesArr.forEach(function(f) {

    if (!f.type.match("image.*")) {
      return;
    }
    storedFiles.push(f);

    var reader = new FileReader();
    reader.onload = function(e) {
      var html = "<div><img src=\"" + e.target.result + "\" data-file='" + f.name + "' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";

      if (device == "mobile") {
        $("#selectedFilesM").append(html);
      } else {
        $("#selectedFiles").append(html);
      }
    }
    reader.readAsDataURL(f);
  });

}

function handleForm(e) {
  e.preventDefault();
  var data = new FormData();

  for (var i = 0, len = storedFiles.length; i < len; i++) {
    data.append('files', storedFiles[i]);
  }

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'handler.cfm', true);

  xhr.onload = function(e) {
    if (this.status == 200) {
      console.log(e.currentTarget.responseText);
      alert(e.currentTarget.responseText + ' items uploaded.');
    }
  }

  xhr.send(data);
}

function removeFile(e) {
  var file = $(this).data("file");
  for (var i = 0; i < storedFiles.length; i++) {
    if (storedFiles[i].name === file) {
      storedFiles.splice(i, 1);
      break;
    }
  }
  $(this).parent().remove();
}
#selectedFiles img,
#selectFilesM img {
  max-width: 200px;
  max-height: 200px;
  float: left;
  margin-bottom: 10px;
}
#userActions input {
  width: auto;
  margin: auto;
}
#selectFiles img,
#selectFilesM img {
  max-width: 200px;
  max-height: 200px;
  float: left;
  margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" id="myForm" name="myForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
  desktop:
  <input data-device="desktop" type="file" id="files" name="files" multiple>
  <div id="selectedFiles"></div>
  <br/>mobile:
  <input data-device="mobile" type="file" id="mobile" name="mobile" multiple>
  <br/>

  <div id="selectedFilesM"></div>
  <button type="submit">Submit</button>
</form>

答案 1 :(得分:2)

您将此视为以下代码段

$("#fileUploadInput").change(function(event){
    $("#filePreviewImage").attr('src',URL.createObjectURL(event.target.files[0]));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fileUploadInput" type="file">
<img id="filePreviewImage" src="" alt="The image preview" height="90" width="160">

只需将"filePreviewImage"替换为your custom selector,无论div如何,它都会填充预览。 享受 ...