Bootstrap fileinput组件封装及使用详解
介绍
通过本文,你可以学习到如何封装或者开发一个前端组件,同时学习bootstrap-fileinput组件的使用,封装后使用更加简单方便。
basefile是admineap框架中基于bootstrap-fileinput的附件上传组件,它支持 支持多文件、在线预览、拖拽上传等功能,封装后basefile主要包括以下功能:
- 弹出窗口的附件上传
- 当前界面的附件上传
- 显示附件明细
- 可编辑的附件明细(删除、预览、不可新增)
关于bootstrap-fileinput的api文档可参考
本文源码已在admineap框架(一个基于adminlte的java开发平台)中开源,可在github下载相关代码:
github:https://github.com/bill1012/admineap
admineap官网:
使用说明
1、初始化
如果需要在当前界面使用附件上传功能(非弹窗方式)则需要在头部引入相关的css和js文件
css文件
<link rel="stylesheet" href="./resources/common/libs/fileinput/css/fileinput.min.css" rel="external nofollow" >
js文件
<script src="./resources/common/libs/fileinput/js/fileinput.js"></script> <script src="./resources/common/libs/fileinput/js/locales/zh.js"></script> <!--basefile组件--> <script src="./resources/common/js/base-file.js"></script>
form表单上还需要配置enctype="multipart/form-data"属性
2、弹窗方式调用
basefile支持弹窗方式打开一个附件上传窗口,点击附件上传后,弹出窗口,上传附件关闭窗口后,上传的附件在type=file的控件回填。
在表单中点击弹窗上传附件:
上传完毕,关闭窗口,附件回填
再次打开上传附件上传窗口时,会把已有的附件回填到附件上传窗口。
配置如下:
html代码
<input type="hidden" name="fileids" id="fileids"> <div class="form-group"> <div class="btn btn-default btn-file" id="uploadfile"> <i class="fa fa-paperclip"></i> 上传附件(max. 10mb) </div> </div> <div class="form-group" id="file_container"> <input type="file" name="file" id="attachment"> </div>
js代码
$("#uploadfile").file({ title: "请上传附件", fileinput: { maxfilesize: 10240, maxfilecount:3 }, fileidcontainer:"[name='fileids']", showcontainer:'#attachment', //显示文件类型 edit=可编辑 detail=明细 默认为明细 showtype:'edit', //弹出窗口 执行上传附件后的回调函数(window:false不调用此方法) window:true, callback:function(fileids,oldfileids){ //更新fileids this.showfiles({ fileids:fileids }); } });
3、本地界面调用
本地界面调用附件上传,如下图所示:
将上传附件嵌入到当前界面方式
上传后的附件可删除、可预览
(目前图片文件可预览,其他文件不可预览,后期将集成txt/xml/html/pdf的预览功能)
配置如下:
html代码
<div class="form-group" id="file_container"> <input type="file" name="file" id="attachment"> </div>
js代码
$("#attachment").file({ fileinput: { maxfilesize: 10240, maxfilecount:3 }, fileidcontainer:"[name='fileids']", window:false });
4、控件参数说明
window 默认为true,弹窗方式打开
title window=true时配置,弹窗的标题,默认为“文件上传”
width window=true时配置,弹窗的宽度,默认900
winid window=true时配置,弹出的id,默认为filewin
fileinput bootstrap-fileinput的配置参数,会覆盖默认配置,比如允许上传哪种类型的附件allowedfiletypes,允许上传最大附件大小maxfilesize,允许上传附件的个数maxfilecount等,具体的配置参数可以查询bootstrap-fileinput的api文档。
fileidcontainer 必须,上传后的附件id存储的位置,id以逗号分隔
showcontainer window=true必须配置,文件上传后回填的区域,window=false时如不配置,则取base-file的初始对象
showtype window=true配置,值为edit或者detail,edit表示回填后可对数据进行删除、预览,detail只能显示,不能删除
callback window=true配置,关闭附件上传的窗口后执行的回调函数(比如更新当前的文件列表),fileids,oldfileids两个参数分别是更新后文件ids和更新前的文件ids
basefile默认配置,basefile的更多实现,请查看basefile源码
basefile.prototype.default = { winid: "filewin", width: 900, title: "文件上传", //通用文件上传界面 url: basepath + "/file/uploader", //默认支持多文件上传 multiple: true, //默认弹出附件上传窗口 window:true, showtype:"detail", fileinput: { language: 'zh', uploadurl: basepath + "/file/uploadmultiplefile", deleteurl:basepath+"/file/delete", uploadasync:false, validateinitialcount:true, overwriteinitial: false, allowedpreviewtypes: ['image'], previewfileicon:'<i class="fa fa-file-o"></i>', previewfileiconsettings: null, slugcallback: function (text) { var newtext=(!text||text=='') ? '' : string(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_'); //去除空格 return newtext.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,""); } } }
5、basefile控件源码
/** * 通用文件管理组件 * @author billjiang qq:475572229 */ (function ($, window, document, undefined) { 'use strict'; var pluginname = 'file'; $.fn[pluginname] = function (options) { var self = $(this); if (this == null) return null; var data = this.data(pluginname); if (!data) { data = new basefile(this, $.extend(true, {}, options)); self.data(pluginname, data); } }; var basefile = function (element, options) { this.element = element; //extend优先级 后面的会覆盖前面的 //alert(this.element.selector); //将容器id传过去便于弹窗获取到basefile对象,如果页面布局不在使用jquery.load方法,则该方法会失效,因为不是一个页面了 options.container = options.container || this.element.selector.replace("#", ""); //初始化文件图标信息 this.getfileiconsettings(); this.options = $.extend(true, {}, this.default, options); //初始化图标信息 this.initfileids(); if(this.options.window) { this.element.click(function () { $(this).data('file').openwin(); }); }else{ //非弹窗形式 if(this.options.multiple) this.element.attr("multiple","multiple"); } //如果配置了附件编辑容器showcontainer(附件列表,可单个删除),则进行初始化 if(this.hasdisplayzone()){ this.showfiles(); } } basefile.prototype.default = { winid: "filewin", width: 900, title: "文件上传", //通用文件上传界面 url: basepath + "/file/uploader", //默认支持多文件上传 multiple: true, //默认弹出附件上传窗口 window:true, showtype:"detail", fileinput: { language: 'zh', uploadurl: basepath + "/file/uploadmultiplefile", deleteurl:basepath+"/file/delete", uploadasync:false, validateinitialcount:true, overwriteinitial: false, allowedpreviewtypes: ['image'], previewfileicon:'<i class="fa fa-file-o"></i>', previewfileiconsettings: null, slugcallback: function (text) { var newtext=(!text||text=='') ? '' : string(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_'); //去除空格 return newtext.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,""); } } } basefile.prototype.getfileinputconfig=function () { return this.options.fileinput; } basefile.prototype.getfileiconsettings = function () { var self = this; ajaxpost(basepath + "/file/icons", null, function (icons) { self.previewfileiconsettings = icons; //console.log(self.previewfileiconsettings); }) } basefile.prototype.openwin = function () { var that = this; var self = $.extend(true, {}, this.options); //深拷贝后删除属性,这样不会通过后台传送过去,防止被xss过滤掉特殊字符 //不需要通过参数config=传递到弹窗的参数可使用delete删除 delete self.callback; delete self.fileids; delete self.showcontainer; delete self.fileidcontainer; delete self.fileinput; /*console.log(this.options); console.log("============="); console.log(self);*/ modals.openwin({ winid: that.options.winid, url: that.options.url + "?config=" + json.stringify(self), width: that.options.width + "px", title: that.options.title, backdrop: "static" }); } basefile.prototype.callbackhandler = function (fileids) { //更新fileids并执行回调函数 var oldfileids = this.options.fileids; this.options.fileids = fileids; this.updatefileids(); if (this.options.callback) { this.options.callback.call(this, fileids, oldfileids); } } //调用成功后执行显示附件 basefile.prototype.showfiles=function(options){ options=options||{}; if(!this.hasdisplayzone()){ modals.error("请配置showcontainer属性,并在容器下配置type=file的input组件"); return; } var fileids=options.fileids||this.options.fileids; if(!fileids&&this.options.window){ $(this.options.showcontainer).hide(); return; } //显示 $(this.options.showcontainer).show(); var filecomponet=$(this.options.showcontainer); var fileresult=this.getfileresult(fileids),preview=fileresult.initialpreview,previewconfig=fileresult.initialpreviewconfig,self=this; //配置三类参数 edit=附件列表(可删除) detail=附件列表(显示) 可上传 var defaultconfig={ initialpreview:preview, initialpreviewconfig:previewconfig }; var config; if(this.options.window){ if(this.options.showtype=="edit"){ //全局配置->本方法默认配置->edit属性下配置->外部参数 config=$.extend({},self.options.fileinput,defaultconfig,{ showremove:false, showupload:false, showclose:false, showbrowse:false, showcaption:false },options); }else if(this.options.showtype=="detail"){ config=$.extend({},self.options.fileinput,defaultconfig,{ showremove:false, showupload:false, showclose:false, showbrowse:false, showcaption:false, initialpreviewshowdelete:false },options); } }else{ config=$.extend({},self.options.fileinput,defaultconfig,{ showclose:false },options); } if(!config){ modals.error("未找到showfiles中的相关配置"); return; } //console.log("config=========="+json.stringify(config)); filecomponet.fileinput('destroy'); filecomponet.fileinput(config).on("filedeleted",function (event,key) { var newfids=self.deletefileids(key,self.options.fileids); self.options.fileids=newfids; self.updatefileids(); }).on("fileuploaded",function(event,data,previewid,index){ var newfids=self.addfileids(data.response.fileids,self.options.fileids); self.options.fileids=newfids; self.updatefileids(); }).on("filebatchuploadsuccess",function (event,data,previewid,index) { var newfids=self.addfileids(data.response.fileids,self.options.fileids); self.options.fileids=newfids; self.updatefileids(); }).on("filezoomhidden", function(event, params) { $(document.body).removeclass('modal-open'); $(document.body).css("padding-right","0px"); }); } /** * 向targetids里删除数据fileids * @param fileids * @param targetids */ basefile.prototype.deletefileids=function(fileids,targetids){ if(!fileids) return targetids; //没有文件删除,其中必有蹊跷 if(!targetids){ modals.error("没有要删除的文件,请检查是否数据没有初始化"); return; } var fileidarr=fileids.split(","); var fresult=targetids.split(","); $.each(fileidarr,function (index,fileid){ //存在则删除 if($.inarray(fileid,fresult)>-1){ fresult.splice($.inarray(fileid,fresult),1); } }) return fresult.join(); } /** * 向targetids里加数据fileids * @param fileids * @param targetids */ basefile.prototype.addfileids=function (fileids,targetids) { if(!fileids)return targetids; var fileidarr=fileids.split(","); var fresult=[]; if(targetids){ fresult=targetids.split(","); } $.each(fileidarr,function (index,fileid){ //不存在,新增 if($.inarray(fileid,fresult)==-1){ fresult.push(fileid); } }) return fresult.join(); } basefile.prototype.updatefileids=function(){ if(this.options.fileidcontainer) $(this.options.fileidcontainer).val(this.options.fileids); } basefile.prototype.initfileids=function(){ //不弹出窗口的话一定要绑定fileidcontainer if(!this.options.window){ if(!this.options.fileidcontainer||!$(this.options.fileidcontainer)){ modals.info("请设置fileidcontainer属性"); return; } } if(!this.options.fileids){ if(this.options.fileidcontainer){ this.options.fileids=$(this.options.fileidcontainer).val(); } } } basefile.prototype.getfileresult=function(fileids){ var ret=null; ajaxpost(basepath+"/file/getfiles",{fileids:fileids},function(result){ ret=result; }); return ret; }; /** * 是否有显示区域 * @returns {boolean} */ basefile.prototype.hasdisplayzone=function(){ if(!this.options.showcontainer){ this.options.showcontainer=this.element.selector; } if(!this.options.showcontainer||!$(this.options.showcontainer)){ return false; } return true; } })(jquery, window, document);
6、后端源码
package com.cnpc.framework.base.controller; import com.cnpc.framework.base.entity.sysfile; import com.cnpc.framework.base.entity.user; import com.cnpc.framework.base.pojo.avatarresult; import com.cnpc.framework.base.pojo.fileresult; import com.cnpc.framework.base.pojo.markdownresult; import com.cnpc.framework.base.pojo.result; import com.cnpc.framework.base.service.uploaderservice; import com.cnpc.framework.util.securityutil; import com.cnpc.framework.utils.dateutil; import com.cnpc.framework.utils.fileutil; import com.cnpc.framework.utils.propertiesutil; import com.cnpc.framework.utils.strutil; import org.apache.commons.fileupload.util.streams; import org.hibernate.criterion.detachedcriteria; import org.hibernate.criterion.order; import org.hibernate.criterion.restrictions; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.responsebody; import org.springframework.web.multipart.multipartfile; import org.springframework.web.multipart.multiparthttpservletrequest; import javax.annotation.resource; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import java.io.*; import java.util.*; @controller @requestmapping("/file") public class uploadercontroller { private static logger logger= loggerfactory.getlogger(uploadercontroller.class); //previewfileiconsettings public static map fileiconmap=new hashmap(); @resource private uploaderservice uploaderservice; static { fileiconmap.put("doc" ,"<i class='fa fa-file-word-o text-primary'></i>"); fileiconmap.put("docx","<i class='fa fa-file-word-o text-primary'></i>"); fileiconmap.put("xls" ,"<i class='fa fa-file-excel-o text-success'></i>"); fileiconmap.put("xlsx","<i class='fa fa-file-excel-o text-success'></i>"); fileiconmap.put("ppt" ,"<i class='fa fa-file-powerpoint-o text-danger'></i>"); fileiconmap.put("pptx","<i class='fa fa-file-powerpoint-o text-danger'></i>"); fileiconmap.put("jpg" ,"<i class='fa fa-file-photo-o text-warning'></i>"); fileiconmap.put("pdf" ,"<i class='fa fa-file-pdf-o text-danger'></i>"); fileiconmap.put("zip" ,"<i class='fa fa-file-archive-o text-muted'></i>"); fileiconmap.put("rar" ,"<i class='fa fa-file-archive-o text-muted'></i>"); fileiconmap.put("default" ,"<i class='fa fa-file-o'></i>"); } //从setting.properties文件中注入文件相对目录(相对目录为显示文件) //@value("${uploaderpath}") 只有配置@config才能注入 private static final string uploaderpath=propertiesutil.getvalue("uploaderpath"); /** * 跳转到通用文件上传窗口 * @return */ @requestmapping(value="/uploader",method = requestmethod.get) public string uploader(string config,httpservletrequest request){ request.setattribute("config",config); return "base/file/file_uploader"; } /** * 通用文件上传接口,存储到固定地址,以后存储到文件服务器地址 */ @requestmapping(value = "/uploadfile", method = requestmethod.post) @responsebody public sysfile uploadfile(@requestparam(value = "file", required = false) multipartfile file, httpservletrequest request, httpservletresponse response) { //todo dosomething return new sysfile(); } /** * 多文件上传,用于uploadasync=false(同步多文件上传使用) * @param files * @param request * @param response * @return */ @requestmapping(value = "/uploadmultiplefile", method = requestmethod.post) @responsebody public fileresult uploadmultiplefile(@requestparam(value = "file", required = false) multipartfile[] files, httpservletrequest request, httpservletresponse response) throws ioexception { system.out.println("the num of file:"+files.length); fileresult msg = new fileresult(); arraylist<integer> arr = new arraylist<>(); //缓存当前的文件 list<sysfile> filelist=new arraylist<>(); string dirpath = request.getrealpath("/"); for (int i = 0; i < files.length; i++) { multipartfile file = files[i]; if (!file.isempty()) { inputstream in = null; outputstream out = null; try { file dir = new file(dirpath+uploaderpath); if (!dir.exists()) dir.mkdirs(); //这样也可以上传同名文件了 string fileprefixformat="yyyymmddhhmmsss"; system.out.println(dateutil.format(new date(),fileprefixformat)); string savedname=dateutil.format(new date(),fileprefixformat)+"_"+file.getoriginalfilename(); string filepath=dir.getabsolutepath() + file.separator + savedname; file serverfile = new file(filepath); //将文件写入到服务器 //fileutil.copyinputstreamtofile(file.getinputstream(),serverfile); file.transferto(serverfile); sysfile sysfile=new sysfile(); sysfile.setfilename(file.getoriginalfilename()); sysfile.setsavedname(savedname); sysfile.setcreatedatetime(new date()); sysfile.setupdatedatetime(new date()); sysfile.setcreateuserid(securityutil.getuserid()); sysfile.setdeleted(0); sysfile.setfilesize(file.getsize()); sysfile.setfilepath(uploaderpath+file.separator+savedname); uploaderservice.save(sysfile); filelist.add(sysfile); /*preview.add("<div class=\"file-preview-other\">\n" + "<span class=\"file-other-icon\"><i class=\"fa fa-file-o text-default\"></i></span>\n" + "</div>");*/ logger.info("server file location=" + serverfile.getabsolutepath()); } catch (exception e) { logger.error( file.getoriginalfilename()+"上传发生异常,异常原因:"+e.getmessage()); arr.add(i); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } else { arr.add(i); } } if(arr.size() > 0) { msg.seterror("文件上传失败!"); msg.seterrorkeys(arr); } fileresult preview=getpreivewsettings(filelist,request); msg.setinitialpreview(preview.getinitialpreview()); msg.setinitialpreviewconfig(preview.getinitialpreviewconfig()); msg.setfileids(preview.getfileids()); return msg; } //删除某一项文件 @requestmapping(value="/delete",method = requestmethod.post) @responsebody public result delete(string id,httpservletrequest request){ sysfile sysfile=uploaderservice.get(sysfile.class,id); string dirpath=request.getrealpath("/"); fileutil.delfile(dirpath+uploaderpath+file.separator+sysfile.getsavedname()); uploaderservice.delete(sysfile); return new result(); } /** * 获取字体图标map,base-file控件使用 */ @requestmapping(value="/icons",method = requestmethod.post) @responsebody public map geticons(){ return fileiconmap; } /** * 根据文件名获取icon * @param filename 文件 * @return */ public string getfileicon(string filename){ string ext= strutil.getextname(filename); return fileiconmap.get(ext)==null?fileiconmap.get("default").tostring():fileiconmap.get(ext).tostring(); } /** * 根据附件ids 获取文件 * @param fileids * @param request * @return */ @requestmapping(value="/getfiles",method = requestmethod.post) @responsebody public fileresult getfiles(string fileids,httpservletrequest request){ string[] fileidarr=fileids.split(","); detachedcriteria criteria=detachedcriteria.forclass(sysfile.class); criteria.add(restrictions.in("id",fileidarr)); criteria.addorder(order.asc("createdatetime")); list<sysfile> filelist=uploaderservice.findbycriteria(criteria); return getpreivewsettings(filelist,request); } /** * 回填已有文件的缩略图 * @param filelist 文件列表 * @param request * @return initialpreiview initialpreviewconfig fileids */ public fileresult getpreivewsettings(list<sysfile> filelist,httpservletrequest request){ fileresult fileresult=new fileresult(); list<string> previews=new arraylist<>(); list<fileresult.previewconfig> previewconfigs=new arraylist<>(); //缓存当前的文件 string dirpath = request.getrealpath("/"); string[] filearr=new string[filelist.size()]; int index=0; for (sysfile sysfile : filelist) { //上传后预览 todo 该预览样式暂时不支持theme:explorer的样式,后续可以再次扩展 //如果其他文件可预览txt、xml、html、pdf等 可在此配置 if(fileutil.isimage(dirpath+uploaderpath+file.separator+sysfile.getsavedname())) { previews.add("<img src='." + sysfile.getfilepath().replace(file.separator, "/") + "' class='file-preview-image kv-preview-data' " + "style='width:auto;height:160px' alt='" + sysfile.getfilename() + " title='" + sysfile.getfilename() + "''>"); }else{ previews.add("<div class='kv-preview-data file-preview-other-frame'><div class='file-preview-other'>" + "<span class='file-other-icon'>"+getfileicon(sysfile.getfilename())+"</span></div></div>"); } //上传后预览配置 fileresult.previewconfig previewconfig=new fileresult.previewconfig(); previewconfig.setwidth("120px"); previewconfig.setcaption(sysfile.getfilename()); previewconfig.setkey(sysfile.getid()); // previewconfig.seturl(request.getcontextpath()+"/file/delete"); previewconfig.setextra(new fileresult.previewconfig.extra(sysfile.getid())); previewconfig.setsize(sysfile.getfilesize()); previewconfigs.add(previewconfig); filearr[index++]=sysfile.getid(); } fileresult.setinitialpreview(previews); fileresult.setinitialpreviewconfig(previewconfigs); fileresult.setfileids(strutil.join(filearr)); return fileresult; } }
总结
本文源码已在admineap框架(一个基于adminlte的java开发平台)中开源,可在github下载相关代码:
github:https://github.com/bill1012/admineap
admineap官网:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。