欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

bootstrap fileinput插件实现预览上传照片功能

程序员文章站 2022-04-29 12:10:17
 效果图如下所示:   具体代码如下:

 效果图如下所示:

bootstrap fileinput插件实现预览上传照片功能 

具体代码如下:

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" >
  <link rel="stylesheet" href="bootstrap-fileinput.css" rel="external nofollow" >
  <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="bootstrap-fileinput.js"></script>
 </head>
 <body>
  <div class="form-group">
   <div class="col-md-8">
    <div class="fileinput fileinput-new" data-provides="fileinput" id="uploadimagediv">
     <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
      <img src="${companyinfo.image}" alt="" />
     </div>
     <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>
     <div>
      <span class="btn default btn-file"> <span
           class="fileinput-new">选择图片</span> <span class="fileinput-exists">更改</span> <input type="file" name="uploadimage" id="uploadimage" /></span>
      <a href="#" rel="external nofollow" class="btn default fileinput-exists" data-dismiss="fileinput">移除</a>
      <span>请选择1m以内图片</span>
     </div>
    </div>
    <div id="titleimageerror" style="color: #a94442"></div>
   </div>
  </div>
 </body>
 <script>
  var handleevent = function() {
   $("#uploadimage").fileupload({
    url: "design/resource/uploadfile",
    datatype: 'json',
    autoupload: false,
    acceptfiletypes: /(gif|jpe?g|png)$/i,
    maxfilesize: 1000000, // 1 mb
    imagemaxwidth: 100,
    imagemaxheight: 100,
    messages: {
     acceptfiletypes: '文件类型不匹配',
     maxfilesize: '文件过大',
     minfilesize: '文件过小'
    }
   }).on("fileuploadadd", function(e, data) {
    $("#titleimageerror").html("");
    $("#addbtn,#updatebtn").off("click").on("click", function() {
     if($("#dialogform").validate().form()) {
      customglobal.blockui("#modalcontent");
      data.submit()
     }
    })
   }).on("fileuploadprocessalways", function(e, data) {
    var index = data.index,
     file = data.files[index];
    if(file.error) {
     $("#titleimageerror").html(file.error)
    }
    $("#addbtn,#updatebtn").prop('disabled', !!data.files.error);
   }).on("fileuploaddone", function(e, data) {
    if(data.result.returnstate == "error") {
     toastr.warning(data.result.returnmsg);
     customglobal.ajaxcallback(data);
     return;
    }
    addnews(data.result.returndata.url);
   });
  }
 </script>
</html>

bootstrap-fileinput.css文件:(github目前正在维护中,之后所有代码上传至我的github)

/*!
 * jasny bootstrap v3.1.3 (http://jasny.github.io/bootstrap)
 * copyright 2012-2014 arnold daniels
 * licensed under apache-2.0 (https://github.com/jasny/bootstrap/blob/master/license)
 */
.btn-file {
 position: relative;
 overflow: hidden;
 vertical-align: middle;
}
.btn-file > input {
 position: absolute;
 top: 0;
 right: 0;
 width: 100%;
 height: 100%;
 margin: 0;
 font-size: 23px;
 cursor: pointer;
 filter: alpha(opacity=0);
 opacity: 0;
 direction: ltr;
}
.fileinput {
 display: inline-block;
 margin-bottom: 9px;
}
.fileinput .form-control {
 display: inline-block;
 padding-top: 7px;
 padding-bottom: 5px;
 margin-bottom: 0;
 vertical-align: middle;
 cursor: text;
}
.fileinput .thumbnail {
 display: inline-block;
 margin-bottom: 5px;
 overflow: hidden;
 text-align: center;
 vertical-align: middle;
}
.fileinput .thumbnail > img {
 max-height: 100%;
}
.fileinput .btn {
 vertical-align: middle;
}
.fileinput-exists .fileinput-new,
.fileinput-new .fileinput-exists {
 display: none;
}
.fileinput-inline .fileinput-controls {
 display: inline;
}
.fileinput-filename {
 display: inline-block;
 overflow: hidden;
 vertical-align: middle;
}
.form-control .fileinput-filename {
 vertical-align: bottom;
}
.fileinput.input-group {
 display: table;
}
.fileinput.input-group > * {
 position: relative;
 z-index: 2;
}
.fileinput.input-group > .btn-file {
 z-index: 1;
}
.fileinput-new.input-group .btn-file,
.fileinput-new .input-group .btn-file {
 border-radius: 0 4px 4px 0;
}
.fileinput-new.input-group .btn-file.btn-xs,
.fileinput-new .input-group .btn-file.btn-xs,
.fileinput-new.input-group .btn-file.btn-sm,
.fileinput-new .input-group .btn-file.btn-sm {
 border-radius: 0 3px 3px 0;
}
.fileinput-new.input-group .btn-file.btn-lg,
.fileinput-new .input-group .btn-file.btn-lg {
 border-radius: 0 6px 6px 0;
}
.form-group.has-warning .fileinput .fileinput-preview {
 color: #8a6d3b;
}
.form-group.has-warning .fileinput .thumbnail {
 border-color: #faebcc;
}
.form-group.has-error .fileinput .fileinput-preview {
 color: #a94442;
}
.form-group.has-error .fileinput .thumbnail {
 border-color: #ebccd1;
}
.form-group.has-success .fileinput .fileinput-preview {
 color: #3c763d;
}
.form-group.has-success .fileinput .thumbnail {
 border-color: #d6e9c6;
}
.input-group-addon:not(:first-child) {
 border-left: 0;
}
bootstrap-fileinput.js:
/* ===========================================================
 * bootstrap: fileinput.js v3.1.3
 * http://jasny.github.com/bootstrap/javascript/#fileinput
 * ===========================================================
 * copyright 2012-2014 arnold daniels
 *
 * licensed under the apache license, version 2.0 (the "license")
 * you may not use this file except in compliance with the license.
 * you may obtain a copy of the license at
 *
 * http://www.apache.org/licenses/license-2.0
 *
 * unless required by applicable law or agreed to in writing, software
 * distributed under the license is distributed on an "as is" basis,
 * without warranties or conditions of any kind, either express or implied.
 * see the license for the specific language governing permissions and
 * limitations under the license.
 * ========================================================== */
+function ($) { "use strict";
 var isie = window.navigator.appname == 'microsoft internet explorer'
 // fileupload public class definition
 // =================================
 var fileinput = function (element, options) {
 this.$element = $(element)
 this.$input = this.$element.find(':file')
 if (this.$input.length === 0) return
 this.name = this.$input.attr('name') || options.name
 this.$hidden = this.$element.find('input[type=hidden][name="' + this.name + '"]')
 if (this.$hidden.length === 0) {
  this.$hidden = $('<input type="hidden">').insertbefore(this.$input)
 }
 this.$preview = this.$element.find('.fileinput-preview')
 var height = this.$preview.css('height')
 if (this.$preview.css('display') !== 'inline' && height !== '0px' && height !== 'none') {
  this.$preview.css('line-height', height)
 }
 this.original = {
  exists: this.$element.hasclass('fileinput-exists'),
  preview: this.$preview.html(),
  hiddenval: this.$hidden.val()
 }
 this.listen()
 }
 fileinput.prototype.listen = function() {
 this.$input.on('change.bs.fileinput', $.proxy(this.change, this))
 $(this.$input[0].form).on('reset.bs.fileinput', $.proxy(this.reset, this))
 this.$element.find('[data-trigger="fileinput"]').on('click.bs.fileinput', $.proxy(this.trigger, this))
 this.$element.find('[data-dismiss="fileinput"]').on('click.bs.fileinput', $.proxy(this.clear, this))
 },
 fileinput.prototype.change = function(e) {
 var files = e.target.files === undefined ? (e.target && e.target.value ? [{ name: e.target.value.replace(/^.+\\/, '')}] : []) : e.target.files
 e.stoppropagation()
 if (files.length === 0) {
  this.clear()
  return
 }
 this.$hidden.val('')
 this.$hidden.attr('name', '')
 this.$input.attr('name', this.name)
 var file = files[0]
 if (this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match(/^image\/(gif|png|jpeg)$/) : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof filereader !== "undefined") {
  var reader = new filereader()
  var preview = this.$preview
  var element = this.$element
  reader.onload = function(re) {
  var $img = $('<img>')
  $img[0].src = re.target.result
  files[0].result = re.target.result
  element.find('.fileinput-filename').text(file.name)
  // if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account
  if (preview.css('max-height') != 'none') $img.css('max-height', parseint(preview.css('max-height'), 10) - parseint(preview.css('padding-top'), 10) - parseint(preview.css('padding-bottom'), 10) - parseint(preview.css('border-top'), 10) - parseint(preview.css('border-bottom'), 10))
  preview.html($img)
  element.addclass('fileinput-exists').removeclass('fileinput-new')
  element.trigger('change.bs.fileinput', files)
  }
  reader.readasdataurl(file)
 } else {
  this.$element.find('.fileinput-filename').text(file.name)
  this.$preview.text(file.name)
  this.$element.addclass('fileinput-exists').removeclass('fileinput-new')
  this.$element.trigger('change.bs.fileinput')
 }
 },
 fileinput.prototype.clear = function(e) {
 if (e) e.preventdefault()
 this.$hidden.val('')
 this.$hidden.attr('name', this.name)
 this.$input.attr('name', '')
 //ie8+ doesn't support changing the value of input with type=file so clone instead
 if (isie) { 
  var inputclone = this.$input.clone(true);
  this.$input.after(inputclone);
  this.$input.remove();
  this.$input = inputclone;
 } else {
  this.$input.val('')
 }
 this.$preview.html('')
 this.$element.find('.fileinput-filename').text('')
 this.$element.addclass('fileinput-new').removeclass('fileinput-exists')
 if (e !== undefined) {
  this.$input.trigger('change')
  this.$element.trigger('clear.bs.fileinput')
 }
 },
 fileinput.prototype.reset = function() {
 this.clear()
 this.$hidden.val(this.original.hiddenval)
 this.$preview.html(this.original.preview)
 this.$element.find('.fileinput-filename').text('')
 if (this.original.exists) this.$element.addclass('fileinput-exists').removeclass('fileinput-new')
  else this.$element.addclass('fileinput-new').removeclass('fileinput-exists')
 this.$element.trigger('reset.bs.fileinput')
 },
 fileinput.prototype.trigger = function(e) {
 this.$input.trigger('click')
 e.preventdefault()
 }
 // fileupload plugin definition
 // ===========================
 var old = $.fn.fileinput
 $.fn.fileinput = function (options) {
 return this.each(function () {
  var $this = $(this),
   data = $this.data('bs.fileinput')
  if (!data) $this.data('bs.fileinput', (data = new fileinput(this, options)))
  if (typeof options == 'string') data[options]()
 })
 }
 $.fn.fileinput.constructor = fileinput
 // fileinput no conflict
 // ====================
 $.fn.fileinput.noconflict = function () {
 $.fn.fileinput = old
 return this
 }
 // fileupload data-api
 // ==================
 $(document).on('click.fileinput.data-api', '[data-provides="fileinput"]', function (e) {
 var $this = $(this)
 if ($this.data('bs.fileinput')) return
 $this.fileinput($this.data())
 var $target = $(e.target).closest('[data-dismiss="fileinput"],[data-trigger="fileinput"]');
 if ($target.length > 0) {
  e.preventdefault()
  $target.trigger('click.bs.fileinput')
 }
 })
}(window.jquery);

总结

以上所述是小编给大家介绍的bootstrap fileinput插件实现预览上传照片功能,希望对大家有所帮助