基于bootstrap的fileinput插件实现上传
用户头像上传的Demo
1.引入文件css文件
<link rel="stylesheet" href="../../libs/bootstrap-3.3.7/css/bootstrap.min.css"><!--引入bootstrap的css文件--> <link rel="stylesheet" href="../../libs/bootstrap-fileinput-master/css/fileinput.min.css"><!--引入fileinput插件的css文件--> <link rel="stylesheet" href="../css/index.css"><!--自己的css文件-->
2.引入js文件
<script src="../../libs/jq/jquery-1.11.3.js"></script><!--引入jq文件--> <script src="../../libs/bootstrap-3.3.7/js/bootstrap.min.js"></script><!--引入bootstrap的js文件--> <script src="../../libs/bootstrap-fileinput-master/js/fileinput.min.js"></script><!--引入fileinput插件js文件--> <script src="../../libs/bootstrap-fileinput-master/js/locales/zh.js"></script><!--引入中文文件-->
3.页面布局
<form class="form form-vertical" id="userImgUploadForm" action="#" method="post" enctype="multipart/form-data"> <div class="row" style="margin:0"> <div class="col-lg-3 col-md-3 col-xs-12 col-sm-4"> <div class="kv-avatar center-block text-center" style="width:200px;"> <input id="avatar-1" name="image" type="file" class="file-loading" required> <div class="help-block"><small>选择头像文件</small></div> </div> </div> <div class="col-sm-8"> <div class="row"> <h1>这里是表单信息</h1> </div> <div class="form-group"> <hr> <div class="text-right"> <button type="button" class="btn btn-primary uploadUserimg">Submit</button> </div> </div> </div> </div> </form> <div id="kv-avatar-errors-1" class="center-block" style="width:800px;display:none"></div>
4.js代码
var btnCust = '<button type="button" class="btn btn-default" title="Add picture tags" ' +
'onclick="alert(\'Call your custom code here.\')">' +
'<i class="glyphicon glyphicon-tag"></i>' +
'</button>';
$("#avatar-1").fileinput({
language:'zh',//设置插件的语言
overwriteInitial: true,
maxFileSize: 1500,//最大文件限制
showClose: false,
showCaption: false,
browseLabel: '',
removeLabel: '',
browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>',
removeIcon: '<i class="glyphicon glyphicon-remove"></i>',
removeTitle: 'Cancel or reset changes',
elErrorContainer: '#kv-avatar-errors-1',
msgErrorClass: 'alert alert-block alert-danger',
defaultPreviewContent: '<img src="../img/default-user-image.png" alt="Your Avatar" style="width:160px">',
layoutTemplates: {main2: '{preview} ' + btnCust + ' {remove} {browse}'},
allowedFileExtensions: ["jpg", "png", "gif"]//上传文件类型设置
});
$('.uploadUserimg').click(function () {
//点击上传按钮,new一个FormData对象
var formData1 = new FormData();
//对象中加入传入的文件,键 为input 的name ,便于后台获取
formData1.append('image', $('#avatar-1')[0].files[0]);
$.ajax({
url: 'http://192.168.0.133:8888/upload',//服务器的上传地址
type: 'POST',
cache: false,//上传图片不需要缓存
data: formData1,
processData: false,//不需要对数据进行处理
contentType: false,
success:function (result) {
console.log(result)//后台返回的数据
//do somethings
}
}).done(function(res) {
console.log(res)
}).fail(function(res) {
console.log(res)
console.log('err')
});
})
貌似。。。没了。。