基于jQuery上传文件插件
2016-06-23 10:22
603 查看
由于最近项目的需求,需要做一个上传文件的插件,支持上传,下载,删除等功能,该插件主要运用了jQuery与jqgrid以及easyui,先贴出主要代码
控制层:
/** * 上传附件插件--uploadFile * 调用示例: * $("#commonUploadBtn").click(function(){ $("#commonUpload").uploadFile({ businessType:"身份甄别",--业务类别 businessID:"2",--业务id filePath:"test",--上传文件的路径 }); 参数说明: 1.businessType 业务类型,对应到数据字典中 2.businessID 业务id 对应数据字典中的code 3.filePath 上传文件的路径,这个需要实现定义好规范,在程序中添加dir */ (function ($) { $.fn.extend({ uploadFile:function(options){ //生成随机数,用来设置image标签的id var fileRandom = Math.floor(Math.random()*100000+1); //初始化内部默认参数 var customParmas = { gridID:"g_"+fileRandom,//上传文件表格ID formID:"form_"+fileRandom,//表单ID pager: "pager_"+fileRandom,//分页ID textfield_fj:"text_"+fileRandom, currentTag : this,//当前标签对象 uploadForm:"uploadForm_"+fileRandom }; //默认参数 var defaultsParams = { upload_url:contextPath + "/uploadAttachment/uploadFile",//上传文件的URL del_url:contextPath + "/uploadAttachment",//删除文件URL list_url:contextPath + "/uploadAttachment",//查询列表的URL down_url:contextPath + "/uploadAttachment/download",//下载 sortname:"createDate",//排序字段,默认:createDate sord: "desc",//排序类型:升序,降序 ,默认降序 }; //装载默然参数和传人的参数对象 var options = $.extend(defaultsParams, options); //渲染视图 var renderView =function(){ var html = ""; html +="<div class='fj_main'>"; html += "<div class='ul1'>"; html += "<span class='fj_top'>上传附件:</span>"; html += "<span>"; html +="<form id='"+options.uploadForm+"' enctype='multipart/form-data' action='"+options.upload_url+"' method='POST'>"; //隐藏域 html += "<input type='hidden' id='businessType' name='businessType' value='"+options.businessType+"' />"; html += "<input type='hidden' id='businessID' name ='businessID' value='"+options.businessID+"' />"; html += "<input type='hidden' id='filePath' name ='filePath' value='"+options.filePath+"' />"; html += "<input type='text' id='"+customParmas.textfield_fj+"' class='mInin2' placeholder='请选择文件'/>"; html += "<input type='button' class='mInbu1' value='选择文件...'/>"; html += "<input type='file' name ='logoFile' class='coninf1' id='logoFile' />"; html += "<form>"; html += "</span>"; html += "</div>"; html += "<ul class='ul2'>"; html += "<li><a href='javascript:void(0)' class='delete'><span><img src='../images/icon/delete.png'></span>移除附件</a></li>"; html += "<li><a href='javascript:void(0)' class='download'><span><img src='../images/icon/page_white_put.png'></span>下载附件</a></li>"; html += "<li><a href='javascript:void(0)' class='upload'><span><img src='../images/icon/accept.png' ></span>确认上传</a></li>"; html += "<li><a href='javascript:void(0)' class='cancel'><span><img src='../images/icon/arrow_refresh.png'></span>重新选择</a></li>"; html += "</ul>"; html += "<div >"; html+="<table id='"+customParmas.gridID+"'></table> "; html+="<div id='"+customParmas.pager+"'></div>"; html += "</div>"; html+="</div>"; $(customParmas.currentTag).prepend(html); initGrid(); bindEvent(); }; //动态绑定事件 var bindEvent = function(){ //绑定选择文件change事件 $("#logoFile").change(function(){ //检查文件的格式 var checkFileTypeResult = checkFileType($("#logoFile").val()); //判断上传的文件的格式是否正确 if(!checkFileTypeResult){ restFileInput(); } //检查文件的大小 var checkFileSizeResult = checkFileSize($("#logoFile").get(0)); if(!checkFileSizeResult){ restFileInput(); }else{ setFileInput(); } }); //绑定确认上传文件事件 $(".upload").click(function(){ uploadFile(); }); //绑定删除上传文件事件 $(".delete").click(function(){ batchDelFile(); }); //绑定取消上传文件事件 $(".cancel").click(function(){ restFileInput(); }); //绑定下载文件事件 $(".download").click(function(){ batchDownloadFile(); }); }; //初始化表格 var initGrid = function(){ $("#"+customParmas.gridID).jqGrid({ url:options.list_url, postData:initSearchCondition(), datatype: "json", width: 600, height:200, multiselect: true, colNames: ["id","附件名称","操作"], colModel: [ { name: "id", index:"id",hidden: true}, { name: "fileName", index:"fileName",align:"center",sortable: true}, { name: "customColumn",formatter:actionFormatter, align:"center",search:false,sortable: false}], pager: "#"+customParmas.pager, sortname: options.sidx, sortorder:options.sord, rowNum: 10, rowList: [10, 20, 30], viewrecords: true, gridview: true, autoencode: true, caption: "附件信息列表", gridComplete: function(){ binCompleteEvent(); } }); }; //表格初始化条件 var initSearchCondition = function (){ var filters = { groupOp : 'AND', rules : [ ], groups:[] }; filters.rules.push( {field : 'businessID',op : 'eq',data :options.businessID} ); return {filters:JSON.stringify(filters)}; } // 给表格绑定加载完的事件 var binCompleteEvent =function(){ //选中行鼠标变为手型 var ids=$("#"+customParmas.gridID).jqGrid('getDataIDs'); for(var i = 0; i < ids.length ; i ++){ var id = ids[i]; $("#"+id).attr("style","cursor:pointer"); } //绑定移除事件 $(".del").click(function(e){ var obj = eval("(" + $(e.target).attr("name") + ")"); deleteFile(obj.id); }); //绑定下载事件 $(".downloadFile").click(function(e){ var obj = eval("(" + $(e.target).attr("name") + ")"); downloadFile(obj.id); }); }; //自定义列 var actionFormatter = function(cellvalue, options, rowObject){ var Obj = "{id:" + "\"" + rowObject.id + "\"" + "}"; var columnTemplate ="<a href='javascript:void(0)'><img src='../images/icon/page_white_put.png' width='16' height='16' title='下载附件' class='downloadFile' name='"+ Obj +"'></a>" + "<a href='javascript:void(0)'><img src='../images/icon/delete.png' width='16' height='16' title='移除附件' class='del' name='"+ Obj +"'></a>"; return columnTemplate; }; //******************************************操作上传附件方法区 //上传文件 var uploadFile = function(){ $.messager.confirm('操作提示','确认上传',function(r){ if (r){ var checkResult = $("#logoFile").val(); if(checkResult){ //判断当前文件夹的文件个数 var ids = $("#"+customParmas.gridID).jqGrid('getDataIDs'); var fileTotal = ids.length; if(fileTotal > 20){ toastr.error("文件个数已超出服务器资源限度,请删除文件后再上传!"); return; } //调用上传文件的方法 $("#"+options.uploadForm).asyncSubmit(option); //进度条 $.messager.progress({ title: '等待', msg: '上传文件中...', text: '正在上传文件,这可能需要一会儿....' }); }else{ toastr.warning("请选择文件上传!"); } } }); }; //回调参数 var option = { callback:function(data){ if(data.result==1){ var msg = ""; if(data.msg){ msg = data.msg; }else{ msg = "上传失败!"; } toastr.error(msg); }else if(data.result==0){ toastr.success("上传成功!"); } //刷新加载表格数据 refreshGrid($("#"+customParmas.gridID), {sortname:options.sortname,sortorder:options.sord}); //重置文件选择框 var checkResult = checkFileSize($("#logoFile").get(0)); if(checkResult){ restFileInput(); setFileInput(); } //关闭进度条 $.messager.progress('close'); } }; //删除文件 //参数说明:id 文件id var deleteFile = function(id){ $.messager.confirm('操作提示','确认移除',function(r){ if (r){ ajax({ url: options.del_url+"/"+id, type: "post", data: "_method=delete", afterOperation: function(){ //刷新表格 refreshGrid($("#"+customParmas.gridID), {sortname:options.sortname,sortorder:options.sord}); } }); } }); }; //批量删除文件 var batchDelFile = function(){ var ids = $("#"+customParmas.gridID).jqGrid ('getGridParam', 'selarrrow'); if(ids==undefined||ids.length ==0 ){ toastr.warning("请选择一个或多个附件移除!"); return; }else{ $.messager.confirm('操作','请确认删除数据',function(r){ if (r){ ajax({ url: options.del_url, type: "post", data: {_method:"delete",ids:ids}, afterOperation: function(){ refreshGrid($("#"+customParmas.gridID), {sortname:options.sortname,sortorder:options.sord}); } }); } }); } }; //下载文件 var downloadFile = function(id){ $.messager.confirm('操作提示','确认下载附件',function(r){ if (r){ downloadForm(id); } }); }; //下载个文件 var batchDownloadFile = function(){ var ids = $("#"+customParmas.gridID).jqGrid ('getGridParam', 'selarrrow'); if(ids==undefined ||ids.length ==0||ids.length!=1 ){ toastr.warning("请选择一个附件下载!"); return; }else{ $.messager.confirm('操作','确认下载附件',function(r){ if (r){ downloadForm(ids[0]); } }); } }; //下载文件隐藏域表单 var downloadForm =function(id){ var form = $(document.createElement('form')).attr("id", "common_downloadForm") .attr('action', options.down_url) .attr('method','get').css("display", "none"); $('body').append(form); $(document.createElement('input')).attr('type', 'hidden').attr('name','id').attr('value', id).appendTo(form); $(form).submit(); }; //重置fileiput var restFileInput = function(){ var file = $("#"+customParmas.textfield_fj).val(); if(file!=null||file!=undefined){ $("#"+customParmas.textfield_fj).val(""); $("#logoFile").val(""); } }; //设置fileiput值 var setFileInput = function(){ var value = $("#logoFile").val(); $("#"+customParmas.textfield_fj).val(value); }; //检查上传文件的大小 var checkFileSize = function(fileInput){ var checkResult = true; var maxSize = 5 * 1024 * 1024; //火狐 if (fileInput.files && fileInput.files[0]) { if(fileInput.files[0].size>(maxSize)){ toastr.warning('您上传的文件超过5M,请重新上传!'); checkResult = false; return checkResult; } } return checkResult; } //判断文件格式 var checkFileType = function (file){ //附件格式 var arrType = ["xls","xlsx","doc","docx","ppt","pptx","pdf","txt","jpeg","png"]; if(file){ var fileType = file.substring(file.lastIndexOf(".")+1); var indexof = $.inArray(fileType, arrType); if(indexof==-1){ toastr.warning("上传文件格式错误,目前仅支持xls/xlsx/doc/docx/ppt/pptx/pdf/txt/jpeg/png!"); return false; } } return true; }; //程序入口 renderView(); } }); })(jQuery);此处上传文件使用了自定义的异步提交表单插件asyncSubmit,主要代码:
/** * option参数 * data:需要传输表单之外的参数json格式 * callback:提交表单之后的回调函数 * check:表单的验证函数 * */ (function ($) { $.fn.asyncSubmit = function (option) { var me = this; //设置验证 if(me.get(0).nodeName.toLowerCase() == "form"){ me.submit(function(e){ //拦截上传form,可做验证 var checkResult = true; if(option.check){ checkResult = option.check(); } return checkResult; }); } //构建内部iframe隐藏提交 var dom = document.createElement("iframe"); var random = "i_" + Math.random() * 1000000; $(dom).attr("name", random).css("display", "none"); $("body").append(dom); //清空额外参数 var extraParamDiv = "extraParamDiv"; $("#" + extraParamDiv).remove(); //设置额外参数 var extraDataArray = new Array(); if(option.data){ if(option.data instanceof Object){ var tempDiv = document.createElement("div"); $(tempDiv).attr("id", extraParamDiv); for(var attr in option.data){ var inputEle = document.createElement("input"); $(inputEle).attr("name", attr); $(inputEle).val(option.data[attr]); extraDataArray.push(inputEle); $(tempDiv).append(inputEle); } me.append(tempDiv); } } me.attr("target", random); if(window["submitCallback"] == null){ window["submitCallback"] = function(data){ //提交完后清除隐藏iframe $(dom).remove() //设置回调 if(option.callback){ option.callback(data); } } } me.submit(); }; })(jQuery);主要的后台程序:
控制层:
package com.bjhy.titan.common.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; 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 com.bjhy.platform.commons.i18n.Message; import com.bjhy.platform.commons.i18n.MessageUtil; import com.bjhy.platform.commons.jqgrid.QueryParams; import com.bjhy.platform.commons.pager.PageBean; import com.bjhy.platform.util.jqgrid.JqGridUtil; import com.bjhy.titan.common.consist.UploadPluginConsist; import com.bjhy.titan.common.domain.AttachmentEntity; import com.bjhy.titan.common.service.UploadAttachmentBizService; /** * 上传附件controller * @author xiaowen * */ @Controller @RequestMapping("/uploadAttachment") public class UploadAttachmentController { @Autowired private UploadAttachmentBizService uploadAttachmentBizService; //查询列表数据 @RequestMapping public @ResponseBody PageBean list(QueryParams queryParams){ PageBean pageBean = JqGridUtil.getPageBean(queryParams); uploadAttachmentBizService.pageQuery(pageBean); return pageBean; } //保存数据 @RequestMapping(value="/uploadFile",method = RequestMethod.POST) public String save(AttachmentEntity attachmentEntity,MultipartFile logoFile,HttpServletRequest request) throws Exception{ try { uploadAttachmentBizService.saveAttchment(attachmentEntity,logoFile); request.setAttribute(UploadPluginConsist.UPLOAD_CALLBACK_DATA, UploadPluginConsist.UPLOAD_RESULT_SUCCESS); } catch (Exception e) { e.printStackTrace(); request.setAttribute(UploadPluginConsist.UPLOAD_CALLBACK_DATA, UploadPluginConsist.createFailMsg(e.getMessage())); } return UploadPluginConsist.UPLOAD_RESULT_PAGE; } //单条删除 @RequestMapping(value="/{id}",method=RequestMethod.DELETE) public @ResponseBody Message delete(@PathVariable String id) throws Exception{ uploadAttachmentBizService.deleteAttachment(id); return MessageUtil.message("attachment.delete.success"); } //批量删除 @RequestMapping(method=RequestMethod.DELETE) public @ResponseBody Message batchDelete(@RequestParam("ids[]") String[] ids) throws Exception { uploadAttachmentBizService.deleteAttachment(ids); return MessageUtil.message("attachment.batchdelete.success"); } //文件下载 @RequestMapping(value="download",method=RequestMethod.GET) public ResponseEntity<byte[]> download(String id) throws Exception { return uploadAttachmentBizService.download(id); } }服务层:
package com.bjhy.titan.common.service; import java.io.IOException; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import com.bjhy.platform.biz.commons.service.BizCommonService; import com.bjhy.titan.common.domain.AttachmentEntity; /** * 上传附件业务接口 * @author xiaowen * */ public interface UploadAttachmentBizService extends BizCommonService<AttachmentEntity, String> { /** * 保存附件数据 * @param attachmentEntity 附件对象 * @param logoFile 文件对象 */ public void saveAttchment(AttachmentEntity attachmentEntity,MultipartFile logoFile); /** * 根据附件id删除附件 * @param ids 附件id * @throws Exception */ public void deleteAttachment(String ...ids)throws Exception; /** * 根据附件名下载附件 * @param id 附件id */ public ResponseEntity<byte[]> download(String id) throws IOException; }服务实现层:
package com.bjhy.titan.common.service.impl; import java.io.File; import java.io.IOException; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import com.bjhy.platform.biz.commons.service.impl.AbstractBizCommonService; import com.bjhy.platform.persist.dao.CommonRepository; import com.bjhy.platform.security.commons.util.UserDetailsUtil; import com.bjhy.platform.util.ExportUtil; import com.bjhy.platform.util.UUIDUtil; import com.bjhy.titan.common.dao.UploadAttachmentRepository; import com.bjhy.titan.common.domain.AttachmentEntity; import com.bjhy.titan.common.service.SystemConfigService; import com.bjhy.titan.common.service.UploadAttachmentBizService; import com.bjhy.titan.common.util.FileUtil; /** * 上传附件业务持久层操作 * @author xiaowen * */ @Service @Transactional public class UploadAttachmentBizServiceImpl extends AbstractBizCommonService<AttachmentEntity, String> implements UploadAttachmentBizService{ @Autowired private UploadAttachmentRepository uploadAttachmentRepository; @Autowired private SystemConfigService systemConfigService; @Override public void saveAttchment(AttachmentEntity attachmentEntity, MultipartFile logoFile) { if(logoFile.getSize() > 5 * 1024 * 1024){ throw new RuntimeException("上传文件不能大于5M"); } try { //文件路径 String filePath = systemConfigService.getAttachmentPath()+File.separator+attachmentEntity.getFilePath(); //显示的文件名 String fileName = logoFile.getOriginalFilename(); //真实的文件名 String file[] = logoFile.getOriginalFilename().split("\\."); String realFileName = file[0]+UUIDUtil.uuid()+"."+file[1]; //封装附件对象 attachmentEntity.setFileName(fileName); attachmentEntity.setRealFileName(realFileName); attachmentEntity.setInputPesion(UserDetailsUtil.getCurrentUser().getUsername()); attachmentEntity.setFilePath(filePath); attachmentEntity.setCreateDate(new Date()); //保存文件至数据库 save(attachmentEntity); //存储附件于服务器上 FileUtil.saveFile(logoFile.getBytes(), filePath, realFileName); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override public void deleteAttachment(String ...ids) throws Exception { for(String id : ids){ //根据id查询文件记录 AttachmentEntity temp = uploadAttachmentRepository.findOne(id); //文件路径 String path = temp.getFilePath()+File.separator+temp.getRealFileName(); //删除服务器上的文件 FileUtil.deleteFile(path); //删除数据库记录 uploadAttachmentRepository.delete(temp); } } @Override public ResponseEntity<byte[]> download(String id) throws IOException { //根据id查询文件记录 AttachmentEntity temp = uploadAttachmentRepository.findOne(id); //文件路径 String filePath = temp.getFilePath()+File.separator+temp.getRealFileName(); return ExportUtil.getResponseEntityByFile(new File(filePath), temp.getFileName()); } @Override protected String getPageQl() { return "select a from AttachmentEntity a where 1=1"; } @Override protected CommonRepository<AttachmentEntity, String> getRepository() { return uploadAttachmentRepository; } }数据访问层:此处主要使用的是spring data
package com.bjhy.titan.common.dao; import com.bjhy.platform.persist.dao.CommonRepository; import com.bjhy.titan.common.domain.AttachmentEntity; public interface UploadAttachmentRepository extends CommonRepository<AttachmentEntity, String> { }
相关文章推荐
- jQuery学习笔记--$.post(),val(),html()
- jquery中live()方法和bind()方法区别分析
- js jquery json ajax区别
- js日历,使用datepicker.js,ui.core.js,jquery-1.7.1.js
- JQuery中的eq()方法
- jQuery根据name属性进行查找的用法分析
- jQuery对象与DOM节点转换
- 区别和详解:jQuery中的 $().each()和$.each()/jQuery.each()
- JQuery记住用户名和密码的具体实现
- jQuery实现查找最近父节点的方法
- 浅谈jquery中的each方法$.each、this.each、$.fn.each
- JQuery async同步异步问题
- Jquery模板
- jquery-toastmessage-plugin 简介信息
- 浅谈jquery中的each方法$.each、this.each、$.fn.each
- jQuery实现查找最近父节点的方法
- jQuery根据name属性进行查找的用法分析
- jquery中live()方法和bind()方法区别分析
- JQuery DIV 动态隐藏和显示的方法
- Jquery 笔记