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


Posted in Javascript onJanuary 23, 2018

 效果图如下所示:

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插件实现预览上传照片功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
javascript replace方法与正则表达式
Feb 19 Javascript
Ext JS 4实现带week(星期)的日期选择控件(实战二)
Aug 21 Javascript
js获取上传文件大小示例代码
Apr 10 Javascript
jQuery判断复选框是否勾选的原理及示例
May 21 Javascript
我的Node.js学习之路(三)--node.js作用、回调、同步和异步代码 以及事件循环
Jul 06 Javascript
jquery判断浏览器后退时候弹出消息的方法
Aug 11 Javascript
js 动态修改css文件用到了cssRule
Aug 20 Javascript
node.js连接mongoDB数据库 快速搭建自己的web服务
Apr 17 Javascript
js动态获取子复选项并设计全选及提交的实现方法
Jun 24 Javascript
AngularJs篇:使用AngularJs打造一个简易权限系统的实现代码
Dec 26 Javascript
jQuery+vue.js实现的多选下拉列表功能示例
Jan 15 jQuery
JQuery使用属性addClass、removeClass和toggleClass实现增加和删除类操作示例
Nov 18 jQuery
php 解压zip压缩包内容到指定目录的实例
Jan 23 #Javascript
three.js 入门案例详解
Jan 23 #Javascript
BootStrap自定义popover,点击区域隐藏功能的实现
Jan 23 #Javascript
vuex的使用及持久化state的方式详解
Jan 23 #Javascript
jquery 输入框查找关键字并提亮颜色的实例代码
Jan 23 #jQuery
js 实现复选框只能选择一项的示例代码
Jan 23 #Javascript
Vue 换肤的示例实践
Jan 23 #Javascript
You might like
MySQL修改密码方法总结
2008/03/25 PHP
php安装ssh2扩展的方法【Linux平台】
2016/07/20 PHP
Zend Framework基于Command命令行建立ZF项目的方法
2017/02/18 PHP
thinkphp中的多表关联查询的实例详解
2017/10/12 PHP
jquery自动完成插件(autocomplete)应用之PHP版
2009/12/15 Javascript
myFocus slide3D v1.1.0 使用方法与下载
2011/01/12 Javascript
JavaScript闭包详解
2015/02/02 Javascript
简化版手机端照片预览组件
2015/04/13 Javascript
JavaScript检查数字是否为整数或浮点数的方法
2015/06/09 Javascript
浅析JavaScript中浏览器的兼容问题
2016/04/19 Javascript
vue中配置mint-ui报css错误问题的解决方法
2017/10/11 Javascript
vue将对象新增的属性添加到检测序列的方法
2018/02/24 Javascript
react中Suspense的使用详解
2019/09/01 Javascript
nuxt配置通过指定IP和端口访问的实现
2020/01/08 Javascript
Python开发的单词频率统计工具wordsworth使用方法
2014/06/25 Python
Python 3.x 新特性及10大变化
2015/06/12 Python
Python 提取dict转换为xml/json/table并输出的实现代码
2016/08/28 Python
Python实现ssh批量登录并执行命令
2016/10/25 Python
Python用threading实现多线程详解
2017/02/03 Python
利用python实现简单的循环购物车功能示例代码
2017/07/05 Python
Python使用pyserial进行串口通信的实例
2019/07/02 Python
在keras中实现查看其训练loss值
2020/06/16 Python
css3动画鼠标放上图片逐渐变大鼠标离开图片逐渐缩小效果
2021/01/27 HTML / CSS
canvas需要在标签里直接定义宽高
2014/12/17 HTML / CSS
小程序瀑布流解决左右两边高度差距过大的问题
2019/02/20 HTML / CSS
巴西家用小家电购物网站:Polishop
2016/08/07 全球购物
美国隐形眼镜网:Major Lens
2018/02/09 全球购物
Java基础知识面试要点
2016/07/29 面试题
int *p=NULL和*p= NULL有什么区别
2014/10/23 面试题
大学生简短的自我评价分享
2014/02/20 职场文书
公司股东合作协议书
2014/09/14 职场文书
国际商务专业毕业生自我鉴定2014
2014/09/27 职场文书
手机销售员岗位职责
2015/04/11 职场文书
2016年中学法制宣传日活动总结
2016/04/01 职场文书
浅谈MySQL函数
2021/10/05 MySQL
Docker下安装Oracle19c
2022/04/13 Servers