使用jquery实现多文件上传预览功能

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />    
    <link href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://cdn.bootcss.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="fileinput.css" rel="stylesheet">
    <script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.bootcss.com/blueimp-load-image/2.10.0/load-image.all.min.js"></script>
</head>
<body>
<table>
   <tr>
     <td>
        <input name="tImage" type="hidden" class="input-image" style=" 500px; height: 265px;">
      </td>
    </tr>    
</table>
</body>
    <script>
 $(function() {
     //遍历图片输出域
     $(".input-image").each(function(){
         var height = $(this).height();
         var width = $(this).width();
         var sizes = new Array();
         $(this).nextAll("img").each(function() {
              var sizeObj = {w:$(this).width(), h:$(this).height(), img:$(this)};
              sizes.push(sizeObj);
         });
          
         //初始化图片预览区域
         $.initFilePreview($(this), sizes, width, height);
    });
 })
// form upload image
jQuery.extend({
     initFilePreview:function(inputImgObj, sizes, width, height) {
        var fieldName = inputImgObj.attr("name");
        var appendToObj = inputImgObj.parent("td");
        var html ="<div class='file-preview' style='height: "+height+"px; "+width+"px;'>"
            html+= "<div class='file-drop-zone'>";
            html+=     "<div class='file-preview-thumbnails file-preview-hbs' style='height:100%;"+(width - 20)+"px;'>";
            html+=     "</div>";
            html+= "</div>";
            html+= "<div class='fileinput-upload-button' style='100%;text-align:center;display:table;margin-top:3px;'>";
            html+=     "<button class='btn btn-success btn-squared fileinput-button' type='button' onclick="$.uploadImages(this, '"+fieldName+"')">上传</button>";
            html+=     "<span class='btn btn-success btn-squared fileinput-button'>";
            html+=         "<span>选择图片</span>";
            html+=         "<input type='file' name='file_"+fieldName+"' onchange='$.selectedUploadImage(this, event)'>";
            html+=     "</span>";
            html+= "</div>";
            html+="</div>";
            appendToObj.append(html);
            $.initImagePreviewFrame(fieldName, sizes);
     },
     initImagePreviewFrame:function(inputName, sizes) {
        var inputObj = $("input[type=hidden][name="+inputName+"]");
        var imagePaths = inputObj.val();
        if(imagePaths != "") {
           var previewFrameDiv = inputObj.parent("td").find("div.file-preview-thumbnails");
           var frameHeight = previewFrameDiv.height();
            
           var height = Math.max(50, frameHeight-65);
           if(!previewFrameDiv) {
              return;
           }
           var imageArray = imagePaths.split(",");
           var timeId = new Date().getTime();
           for(var i = 0; i < imageArray.length; i++) {
              var sizeObj = sizes[i];
              var sizeH = sizeObj.h;
              var sizeW = sizeObj.w;
              var width = (height/sizeH) * sizeW;
              previewFrameDiv.append($.createFilePreviewFrame(inputName, timeId + i, height, width));
              imageObj = sizeObj.img;
              var cloneImg = imageObj.clone()
              cloneImg.width(width);
              cloneImg.height(height);
              cloneImg.show();
              imageObj.remove();
              $("#imagePreview-" + (timeId + i)).append(cloneImg);
              $("#preview-" + (timeId + i)).attr("filePath", imageArray[i]);
           }
        }
     },
 
     createFilePreviewFrame:function(fieldName, id, height, width) {
         var html = "<div class='file-preview-frame' id='preview-" + id + "'>";
             html+= "<div id='imagePreview-"+ id +"' style='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = scale); "+width+"px; height: "+height+"px;'>";
             html+= "</div>";
             html+= "<div class='file-thumbnail-footer'>";
             html+=    "<div class='file-actions'>";
             html+=      "<div class='file-footer-buttons'>";
             html+=        "<button type='button' class='kv-file-remove btn btn-xs btn-default' title='删除文件' onclick="$.deleteFilePreviewFrame("+id+", '"+fieldName+"')">";
             html+=          "<i class='fa fa-trash-o red icon-size-14'></i>";
             html+=        "</button>";
             html+=      "</div>";
             html+=    "</div>";
             html+=  "</div>";
             html+= "</div>";
         return html;
     },
     createFileinputButton:function(fieldName) {
         var html = "<span class='btn btn-success btn-squared fileinput-button'>";
             html+=    "<span>选择图片</span>";
             html+=    "<input type='file' name='file_"+fieldName+"' onchange='$.selectedUploadImage(this, event)'>";
             html+= "</span>";
         return html;
     },
     deleteFilePreviewFrame:function(id, fieldName) {
          
         var preview = $("#preview-" + id);
         var filePath = preview.attr("filePath");
 
           
          var previewFrameDiv = preview.parent(".file-preview-thumbnails");
           
          //delete preview image
          preview.remove();
          //delete file upload button
          $("#file-" + id).parent("span").remove();
           
          $.deleteImage(previewFrameDiv, fieldName);
     },
     selectedUploadImage:function(obj, e) {
         var timeId = new Date().getTime();
 
         var fileObj = $(obj);
         fileObj.attr("id", "file-" + timeId);
          
         var fileName = fileObj.attr("name");
         var fieldName = fileName.substring("file_".length, fileName.length);
 
         var btnDiv = fileObj.closest(".fileinput-upload-button");
         btnDiv.append($.createFileinputButton(fieldName));
 
         var previewFrameDiv = fileObj.closest(".fileinput-upload-button").prev().find(".file-preview-thumbnails");
         var frameHeight = previewFrameDiv.height() - 35;
         var frameWidth = previewFrameDiv.width() - 20;
          
         var height = Math.max(50, frameHeight);
         var width = Math.max(50, frameWidth)/2;
         previewFrameDiv.append($.createFilePreviewFrame(fieldName, timeId, height, width));
 
         $.displayPreviewImage(timeId, e, height, width);
         //hide current file button
         fileObj.parent("span").hide();
     },
     displayPreviewImage:function(id, e, height, width) {
         if(!$.support.leadingWhitespace){
               var obj = document.getElementById("file-" + id);
               obj.select();
               var path = document.selection.createRange().text;
 
               var sizes = $.getIePreviewImageSize(id, path);
               var hPercent = height/sizes[1];
               var width = hPercent * sizes[0];
 
               var picpreview=document.getElementById("imagePreview-" + id);
               try{
                    picpreview.style.width = width;
                    picpreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = path;
               } catch (ex){
                    alert("file path error!");
                    return false;
               }
           } else {
              var file = e.target.files[0];
              loadImage(
                file,
                function(img) {
                    $("#imagePreview-" + id).prepend(img);
                },
                {maxWidth: width, maxHeight:height}
            );
          }
     },
     getIePreviewImageSize:function(id, path) {
           var picpreview=document.getElementById("imagePreview-" + id);
           var tempDiv=document.createElement("div");  
           picpreview.appendChild(tempDiv);  
           tempDiv.style.width="10px";  
           tempDiv.style.height="10px";  
           tempDiv.style.diplay="none";  
           tempDiv.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image);";  
           tempDiv.id="previewTemp";  
           tempDiv.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=path;  
           var width=tempDiv.offsetWidth;  
           var height=tempDiv.offsetHeight;  
           picpreview.removeChild(tempDiv);
 
           var sizes = new Array();
           sizes.push(width);
           sizes.push(height);
 
           return sizes;
     },
     uploadImages:function(obj, fileName) {
          var flag = false;
          $("input[type='file'][name='file_"+fileName+"']").each(function(){
              var fileName = $(this).val();
              if(fileName != "" && (fileName.endWith(".png") || fileName.endWith(".PNG") ||
              fileName.endWith(".jpg") || fileName.endWith(".JPG") || fileName.endWith(".jpeg") || fileName.endWith(".JPEG")
              || fileName.endWith(".bmp") || fileName.endWith(".BMP") || fileName.endWith(".gif") || fileName.endWith(".GIF"))) {
                 flag = true;
              }
          });
           
          if(!flag) {
              layer.alert('请选择图片上传!', {icon: 0});
              return false;
          }
           
          var fileObj = $(obj).closest(".fileinput-upload-button").prev();
          var previewFrameDiv = fileObj.find(".file-preview-thumbnails");
          var hiddenInput = $("input[type=hidden][name="+fileName+"]");
           
          var loadIdx = layer.load();
           
          $.ajaxFileUpload({
              url:form.uploadUrl,
              secureuri:false,
              fileElementName:"file_" + fileName,
              dataType: 'json',
              success: function(data, status){
                 layer.close(loadIdx);
                 if(data.code == 411) {
                     layer.alert('图片最大不能超过' + data.error, {icon: 0});
                     return false;
                 }
                  
                 var imageData = data.value;
                 layer.msg('图片上传成功', {time: 1000, shadeClose:true});
                 var filePaths = "";
                 var index = 0;
                 previewFrameDiv.find(".file-preview-frame").each(function(){
                     if(!$(this).attr("filePath") && index < imageData.length) {
                        $(this).attr("filePath", imageData[index]);
                        index ++;
                     }
                      
                     filePaths += $(this).attr("filePath");
                     filePaths += ",";
                 });
                  
                 if(filePaths.length > 1) {
                    filePaths = filePaths.substring(0, filePaths.length - 1);
                 }
                  
                 hiddenInput.val(filePaths);
              }, error: function (data, status, e) {
                 layer.close(loadIdx);
                 layer.alert('上传失败!', {icon: 0});
              }
          });
           
          return false;
     },
     deleteImage:function(previewFrameDiv, fileName) {
           var hiddenInput = $("input[type=hidden][name="+fileName+"]");
           var filePaths = "";
           previewFrameDiv.find(".file-preview-frame").each(function(){
                 if($(this).attr("filePath")) {
                     filePaths += $(this).attr("filePath");
                     filePaths += ",";
                 }
           });
            
           if(filePaths.length > 1) {
                filePaths = filePaths.substring(0, filePaths.length - 1);
           }
           hiddenInput.val(filePaths);
     }
});
    </script>
</html>




fileinput.css代码如下


.file-loading {
    top: 0;
    right: 0;
    25px;
    height: 25px;
    font-size: 999px;
    text-align: right;
    color: #fff;
    background: transparent url('../img/loading.gif') top left no-repeat;
    border: none;
}

.file-object {
    margin: 0 0 -5px 0;
    padding: 0;
}

.btn-file {
    position: relative;
    overflow: hidden;
}

.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min- 100%;
    min-height: 100%;
    text-align: right;
    opacity: 0;
    background: none repeat scroll 0 0 transparent;
    cursor: inherit;
    display: block;
}

.file-caption-name {
    display: inline-block;
    overflow: hidden;
    height: 20px;
    word-break: break-all;
}

.input-group-lg .file-caption-name {
    height: 25px;
}

.file-preview-detail-modal {
    text-align: left;
}

.file-caption-disabled {
    background-color: #EEEEEE;
    cursor: not-allowed;
    opacity: 1;
}

.file-preview {
    /*border-radius: 5px;
    border: 1px solid #ddd;
   
    100%;
    */
     margin-bottom: 5px;
     padding: 5px;
}

.file-preview-frame {
    display: inline-block;
    margin-left: 10px;
    border: 1px solid #ddd;
    box-shadow: 1px 1px 5px 0 #a2958a;
    padding: 3px;
    text-align: center;
    vertical-align: middle;
}

.file-preview-hbs {
    overflow-y: hidden;
    overflow-x: auto;
    white-space: nowrap;
    padding-bottom:20px;
}

.file-preview-frame:not(.file-preview-error):hover {
    box-shadow: 3px 3px 5px 0 #333;
}

.file-preview-image {
    height: 160px;
    vertical-align: middle;
}

.file-preview-text {
    text-align: left;
    160px;
    margin-bottom: 2px;
    color: #428bca;
    background: #fff;
    overflow-x: hidden;
}

.file-preview-other {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    160px;
    height: 160px;
    border: 2px solid #999;
    border-radius: 30px;
    opacity: 0.8;
}

.file-actions, .file-other-error {
    text-align: left;
}

.file-icon-lg {
    font-size: 1.2em;
}

.file-icon-2x {
    font-size: 2.4em;
}

.file-icon-4x {
    font-size: 4.8em;
}

.file-input-new .file-preview, .file-input-new .close, .file-input-new .glyphicon-file,
.file-input-new .fileinput-remove-button, .file-input-new .fileinput-upload-button,
.file-input-ajax-new .fileinput-remove-button, .file-input-ajax-new .fileinput-upload-button {
    display: none;
}

.fileinput-upload-button > span {
    margin-left:8px;
}

.file-actions {
    margin-top: 5px;
}

.file-footer-buttons {
    float: right;
}

.file-upload-indicator {
    padding-top: 2px;
    cursor: default;
    opacity: 0.8;
    60%;
}

.file-upload-indicator:hover {
    font-weight: bold;
    opacity: 1;
}

.file-footer-caption {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    160px;
    text-align: center;
    padding-top: 4px;
    font-size: 11px;
    color: #777;
    margin: 5px auto 10px auto;
}

.file-preview-frame:not(.file-preview-error) .file-footer-caption:hover {
    color: #000;
}

.file-drop-zone {
    border: 1px dashed #aaa;
    height: 100%;
    text-align: center;
    vertical-align: middle;
    padding: 2px;
}

.file-drop-zone-title {
    color: #aaa;
    font-size: 40px;
    padding: 85px 10px;
}

.file-highlighted {
    border: 2px dashed #999 !important;
    background-color: #f0f0f0;
}

.file-uploading {
    background: url('../img/loading-sm.gif') no-repeat center bottom 10px;
    opacity: 0.65;
}

.file-error-message .close {
    margin-top: 5px;
}

.file-thumb-progress .progress, .file-thumb-progress .progress-bar {
    height: 10px;
    font-size: 9px;
    line-height: 10px;
}

.file-thumbnail-footer {
    position: relative;
}

.file-thumb-progress {
    position: absolute;
    top: 22px;
    left: 0;
    right: 0;
}

/* IE 10 fix */
.btn-file ::-ms-browse {
    100%;
    height:100%;
}


.fileinput-button {
  position: relative;
  overflow: hidden;
  display: inline-block;
  padding: 4px 6px !important;
}
.fileinput-button input {
  position: absolute;
  top: 0;
  right: 0;
  margin: 0;
  opacity: 0;
  -ms-filter: 'alpha(opacity=0)';
  /*font-size: 200px;*/
  font-size: 30px;
  direction: ltr;
  cursor: pointer;
}

/* Fixes for IE < 8 */
@media screen9 {
  .fileinput-button input {
    filter: alpha(opacity=0);
    font-size: 100%;
    height: 100%;
  }
}


原文地址:https://www.cnblogs.com/blackshine/p/6426464.html