extjs 附件上传代码

1.前端代码

            //附件管理

        me.attachmentMainFieldSet=Ext.create('app.common.attachment.AttachmentMainFieldSet',{
            //传递编码:识别标识 查找时用
            param:{code:'COOLECTION_APPLY'}
        });

/**
 * 附件上传
 */
Ext.define('app.common.attachment.AttachmentMainFieldSet', {
    extend : 'Ext.form.FieldSet',
    layout : 'anchor',
    title:'附件列表',
    bodyStyle : 'margin:6px;',
    border:true,
    isEdit:true,//是否可修改,true->是,则显示上传跟删除按钮;false->否,则隐藏上传跟删除按钮
    initComponent : function() {
        var me =this;
        me.attachmentGrid =Ext.create('app.common.attachment.AttachmentGrid',{
            isEdit:me.isEdit,
            param: me.param
        });
        me.items=[me.attachmentGrid];
        this.callParent(arguments);
    },
    //获取附件ids
    getAttachmentIds:function(){
        return me.attachmentGrid.getAttachmentIds();
    },
    removeData:function(){
        var me = this;
        me.attachmentGrid.removeData();
    }
});
 

 

/**
 * 附件列表
 */
Ext.define('app.common.attachment.AttachmentGrid',{
    extend : 'app.system.common.CommonGrid',
    border:true, 
    minHeight:200,
    isEdit:true,//是否可修改,true->是,则显示上传跟删除按钮;false->否,则隐藏上传跟删除按钮
    serviceTableId:null,
    param:null,
    //初始化
    initComponent : function() {
        var me =this;
        me.initStore();
        me.initResultGridPanel();
        if(me.isEdit){
            me.attachmentGridToolBar=Ext.create('Ext.toolbar.Toolbar',{
                items:[{
                    text : '上传',
                    iconCls : 'bt-upload',
                    handler : function() {
                        me.handleUpload();  
                    }
                },
                {
                    text : '删除',
                    iconCls : 'fa fa-trash-o',
                    handler : function() {
                        me.handleDelete();
                    }
                }
                ]
            });
            me.tbar=me.attachmentGridToolBar;
        }
        this.callParent(arguments);
    },

    /**
     * 初始化数据源
     */
    initStore : function() {
        var me = this;
        me.store = Ext.create('app.system.common.CommonGridStore', {
            autoSelectFirst:false,
            autoLoad : true,
            proxy : {
                type : 'ajax',
                url:'attachmentCommonController/findAttachmentList.do',
                extraParams : {
                    serviceTableId: me.serviceTableId
                },
                reader : {
                    type : 'json',
                    rootProperty : 'records',
                    totalProperty : 'totalCount'
                }
            }

        });
    },
    /**
     * 初始化查询结果表格
     */
    initResultGridPanel : function() {
        var me = this;
        this.columns =[
            {   
                text: '名称',  
                minWidth : 300,
                autoWidth : true,
                dataIndex:'name'
            },
            {   text: '上传时间',  
                minWidth : 100,
                autoWidth : true,
                dataIndex:'uploadTime'
            },{
                text: '查看', 
                xtype:"actioncolumn",
                iconCls : 'bt-search  bt-actioncolumn',
                tooltip:"只能查看图片",
                minWidth : 80,
                autoWidth : true,
                align:'center',
                handler:function(view,rowIndex,colIndex){
                    var record=view.getStore().getAt(rowIndex);
                    me.handleViewImage(record);
                }
            },{
                text: '下载', 
                xtype:"actioncolumn",
                iconCls : 'bt-download  bt-actioncolumn',
                tooltip:"下载",
                minWidth : 80,
                autoWidth : true,
                align:'center',
                handler:function(view,rowIndex,colIndex){
                    var record=view.getStore().getAt(rowIndex);
                    me.handleDownload(record);
                }
            }];
        
    },
    /**
     * 查询数据
     */
    queryData:function(params){
        var me =this;
        me.store.queryByConditions(params);
    },
    /**
     * 清除数据
     */
    removeData:function(){
        var me = this;
        me.store.removeAll();
    },
    /**
     * 重新加载
     */
    reLoad:function(){
        var me =this;
        me.store.load();
    },
    /**
     * 文件上传
     */
    handleUpload:function(){
        var me = this;
        if(!me.attachmentImportWindow){
            me.attachmentImportWindow = Ext.create('app.common.attachment.AttachmentImportWindow',{
                importUrl:'attachmentCommonController/fileUpload.do',
                grid:me,
                param : me.param
            });
        }
        me.attachmentImportWindow.removeData();
        me.attachmentImportWindow.show();
    },
    /**
     * 删除文件
     */
    handleDelete:function(){
        var me = this;
        var selectRecords = me.getSelection();
        if(selectRecords && selectRecords.length<=0){
            Ext.toastWarn('请选择要删除的记录!');
            return false;
        }
        var attachmentId = selectRecords[0].data.attachmentId?selectRecords[0].data.attachmentId:'';
        Ext.Msg.confirm('友情提示','删除之后无法恢复文件,您确定要删除所选的文件吗?',function(btn) {
            if (btn == 'yes') {
                var myMask = new Ext.LoadMask({
                    msg : "正在删除,请稍候......",
                    target : me
                });
                myMask.show();
                $.ajax({  
                    url :'attachmentCommonController/deleteFile.do',
                    type : "POST",  
                    datatype:"json",  
                    data : {
                        attachmentId:attachmentId
                    },  
                    success : function(data, stats) {  
                        var resultFlag = data.resultFlag;
                        if("fail"==resultFlag){
                            Ext.toastWarn(data.msg);
                            myMask.hide();
                        }else{
                            Ext.toastInfo('操作成功');
                            myMask.hide();
//                            me.reLoad();
                            me.store.remove(selectRecords[0]);
                        }
                        return false;
                    },  
                    error : function(data) {  
                        Ext.toastWarn('操作失败!');
                        myMask.hide();
                        return false;
                    }  
                }); 
            }
        });
        
    },
    /**
     * 查看图片
     */
    handleViewImage : function(record){
        var me = this;
        var fileName = record.data.name;
        var startIndex = fileName.lastIndexOf(".");
        var fileType = '';
        if(startIndex != -1){
            fileType = fileName.substring(startIndex+1, fileName.length)
        }
        if( fileType != "bmp" && fileType != "png" && fileType != "gif" && fileType != "jpg" && fileType!= "jpeg"){
            Ext.toastInfo('只能查看图片文件!');
          return;
        }
        if (!me.attachmentViewImageWindow) {
            me.attachmentViewImageWindow = Ext.create('app.common.attachment.AttachmentViewImageWindow');
        }
        me.attachmentViewImageWindow.display(record.data);
    },
    /**
     * 文件下载
     */
    handleDownload : function(record){
        var me = this;
        var fileName = record.data.name;
        var filePath = record.data.relativePath;
        if(!fileName || !filePath){
            Ext.toastInfo('附件不存在!');
        }
        me.down(filePath,fileName);
    },
    down:function(filePath,fileName){
        var me = this;
        var myMask = new Ext.LoadMask({
            msg : "正在下载,请稍候......",
            target : me
        });
        myMask.show();
        
        $.ajax({  
            url :'attachmentCommonController/isFileExists.do',        
            type : "POST",  
            datatype:"json",  
            data : {filePath:filePath},  
            success : function(data, stats) {  
                var resultFlag = data.resultFlag;
                if("fail"==resultFlag){
                    Ext.toastWarn(data.msg);
                    myMask.hide();
                }else{
                    window.location.href = 'attachmentCommonController/download.do?filePath='+ filePath + '&fileName='+fileName;
                    myMask.hide();
                }
                return false;
            },  
            error : function(data) {  
                Ext.toastWarn('下载失败!');
                myMask.hide();
                return false;
            }  
        }); 
    },
    //获取选中的附件id
    getAttachmentIds:function(){
        var me = this;
        var ids = [];
        Ext.each(me.store.getRange(),function(record){
            var attachmentId =record.get("attachmentId");
            ids.push(attachmentId);
        });
        return ids;
    }
});
 

 

/**
 * 文件上传
 */
Ext.define('app.common.attachment.AttachmentImportWindow', {
    extend : 'Ext.window.Window',
    closeAction:'hide',
    height : 180,
    width : 480,
    layout : 'fit',
    modal : true,
    param : null,
    grid : null,
    importUrl : null,
    title : "附件上传",
    initComponent : function() {
        var me =this;
        me.editForm = Ext.create('Ext.form.Panel', {
               layout: "anchor", 
            border:false,
            items: [{
                margin : '30 10 0 10',
                xtype : 'filefield',
                name : 'file',
                fieldLabel : '选择上传文件*',
                width : 440,
                allowBlank : false,
                buttonText : '浏览',
                buttonConfig : {
                    iconCls : 'fa fa-folder-open-o',
                },
            }]
        });
        me.items=[me.editForm];
        me.initBtns();
          
        this.callParent(arguments);
    },
    initBtns:function(){
        var me = this;
        
        me.uploadBtn = Ext.create('Ext.button.Button', {
            text : '上传',
            iconCls : 'fa fa-upload',
            handler : function(){
                  me.doUpload(this);
              }
        });
        me.closeBtn = Ext.create('Ext.button.Button', {
            text : '关闭',
            iconCls : 'fa fa-close',
            handler : function(){
                  me.hide();
              }
        });
        me.buttons=[me.uploadBtn,me.closeBtn];
        
    },
    doUpload:function(file){
        var me =this;
        if(!me.editForm.getForm().isValid()){
            Ext.toastWarn('请选择需要上传的文件!');
            return false;
        };
        var isSize = me.validateImageSize();
        if(isSize){
            Ext.toastInfo('所选的文件不能大于5M!');
            return;
        }
        if (me.editForm.isValid()) {
            me.editForm.submit({
                url : me.importUrl,
                waitMsg : '正在上传中,请稍候...',
                params : me.param,
                timeout : 1200000,
                success : function(form, action) {
                    var success = action.result.success;
                    var resultMsg = action.result.result;
                    Ext.toastInfo('所选的文件已成功上传!');
                    me.grid.store.add(resultMsg);
                    
                    me.hide();
                },
                failure : function(form, action) {
                    if(action.result){
                        Ext.toastErrorInfo(action.result.result);// 错误信息
                    } 
                }
            })
        }
    },
    //验证图片大小
    validateImageSize : function (){
        //取控件中的input元素
//        var inputs = field.getElementsByTagName('input');
        var inputs = document.getElementsByName('file');
        var fileInput = null;
        var il = inputs.length;
        //取出input 类型为file的元素
        for(var i = 0; i < il; i ++){
            if(inputs[i].type == 'file'){
                fileInput = inputs[i];
                break;
            }
        }
        if(fileInput != null){
            var fileSize = getFileSize(fileInput);
            //允许上传不大于5M的文件
            return fileSize > 1024*5;
        }
        return false;
    },
    //计算文件大小,返回文件大小值,单位K
    getFileSize : function (target) {
        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        var fs = 0;
        if (isIE && !target.files) {
            var filePath = target.value;
            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
            var file = fileSystem.GetFile(filePath);
            fs = file.Size;
        } else if (target.files && target.files.length > 0) {
            fs = target.files[0].size;
        } else {
            fs = 0;
        }
        if (fs > 0) {
            fs = fs / 1024;
        }
        return fs;
    },
    removeData:function(){
        var me = this;
        me.editForm.getForm().resetToNull();
    }    
});
 

/**
 * 查看附件图片
 */
Ext.define('app.common.attachment.AttachmentViewImageWindow',{
    extend : 'Ext.window.Window',
    layout : 'fit',
    modal : true,
    maximizable : true,
    closeAction : 'hide',
    bodyStyle : 'padding : 2px 2px 0',
    shadowOffset : 30,
    layout : 'fit',
    width : 750,
    height : 390,
    buttons : [],
    buttonAlign : 'center',
    title : '查看附件图片',
    imageUrl : null,
    /**
     * 
     * 初始化组件
     */
    initComponent : function() {
        var me = this;
        me.initForm();
        me.initBtns();
        this.callParent(arguments);
    },
    initForm :function(){
        var me = this;
        me.changingImage = Ext.create('Ext.Img', {
            src: '',
            renderTo: Ext.getBody()
        });
        me.editForm = Ext.create('Ext.form.Panel', {
            layout : 'anchor',
            autoScroll : true,
            bodyStyle : 'padding:6px;margin-top:12px;',
            border : false,
            items: [me.changingImage]
        });
        me.items = [ me.editForm];
    },
    // 初始化按钮
    initBtns : function() {
        var me = this;
        if (!me.buttons) {
            me.buttons = [];
        }
        me.closeBtn = Ext.create('Ext.button.Button', {
            text : '关闭',
            iconCls : 'fa fa-close',
            handler : function() {
                me.hide();
            }
        });
        me.buttons = [me.closeBtn];
    },
    // 显示
    display : function(attachment) {
        var me = this;
        // 用程序修改image标签的src参数
        me.changingImage.setSrc('attachmentCommonController/viewImage.do?relativePath='+ attachment.relativePath);
        me.show();
    },
});
 

2.后端controller代码

                                                                                                          
 @RequestMapping({"/findSystemAttachment.do"})                                                            
 @ResponseBody                                                                                            
 public Page<AttachmentVo> findSystemAttachment(AttachmentVo attachmentVo, HttpSession paramHttpSession)  
 {                                                                                                        
   attachmentVo = attachmentVo != null ? attachmentVo : new AttachmentVo();                               
                                                                                                          
   return attachmentService.findSystemAttachment(attachmentVo);                                           
 }                                                                                                        

                                                                                                          
 @RequestMapping({"/findSystemAttachment.do"})                                                            
 @ResponseBody                                                                                            
 public Page<AttachmentVo> findSystemAttachment(AttachmentVo attachmentVo, HttpSession paramHttpSession)  
 {                                                                                                        
   attachmentVo = attachmentVo != null ? attachmentVo : new AttachmentVo();                               
                                                                                                          
   return attachmentService.findSystemAttachment(attachmentVo);                                           
 }                                                                                                        

                                                                                                          
 @RequestMapping({"/findSystemAttachment.do"})                                                            
 @ResponseBody                                                                                            
 public Page<AttachmentVo> findSystemAttachment(AttachmentVo attachmentVo, HttpSession paramHttpSession)  
 {                                                                                                        
   attachmentVo = attachmentVo != null ? attachmentVo : new AttachmentVo();                               
                                                                                                          
   return attachmentService.findSystemAttachment(attachmentVo);                                           
 }                                                                                                        

                                                                                                                                                                       
@ResponseBody                                                                                                                                                          
@RequestMapping(value={"/fileUpload.do"}, produces={"application/json; charset=utf-8"})                                                                                
protected Object doFileUpload(HttpSession paramHttpSession, @RequestParam("file") MultipartFile file, HttpServletResponse response, @RequestParam("code") String code) 
{                                                                                                                                                                      
  UserSession userSession = SessionListener.getInstance().getUserSession(paramHttpSession);                                                                            
                                                                                                                                                                       
  code = StringUtils.isBlank(code) ? "attachment_code_other" : code;                                                                                                   
  return attachmentService.addFile(file, code, userSession);                                                                                                           
}                                                                                                                                                                      
                                                                                                                                                                       
                                                                                                                                                                       
                                                                                                                                                                       
                                                                                                                                                                       
@ResponseBody                                                                                                                                                          
@RequestMapping(value={"/deleteFile.do"}, produces={"application/json; charset=utf-8"})                                                                                
protected ResultCallback deleteFile(HttpSession paramHttpSession, String attachmentId)                                                                                 
{                                                                                                                                                                      
  UserSession userSession = SessionListener.getInstance().getUserSession(paramHttpSession);                                                                            
  if (StringUtils.isBlank(attachmentId)) {                                                                                                                             
    return ResultCallback.fail("附件ID为空!");                                                                                                                             
  }                                                                                                                                                                    
  return attachmentService.deleteFile(userSession, attachmentId);                                                                                                      
}                                                                                                                                                                      
                                                                                                                                                                       
                                                                                                                                                                       
                                                                                                                                                                       
                                                                                                                                                                       
@ResponseBody                                                                                                                                                          
@RequestMapping(value={"/findAttachmentList.do"}, produces={"application/json; charset=utf-8"})                                                                        
protected Page<Attachment> findAttachmentList(String serviceTableId, String code)                                                                                      
{                                                                                                                                                                      
  if (StringUtils.isBlank(serviceTableId)) {                                                                                                                           
    return new Page();                                                                                                                                                 
  }                                                                                                                                                                    
  return attachmentService.findAttachmentList(serviceTableId, code);                                                                                                   
}                                                                                                                                                                      
                                                                                                                                                                       
/* Error */                                                                                                                                                            
@RequestMapping(value={"/viewImage.do"}, produces={"application/json; charset=utf-8"})                                                                                 
protected void viewImage(HttpServletResponse response, Attachment attachment)                                                                                          
  throws IOException                                                                                                                                                   
{                                                                                                                                                                      
                                                                                                                                                                              
   @RequestMapping({"/isFileExists.do"})                                                                                                                                      
   @ResponseBody                                                                                                                                                              
   public ResultCallback isFileExists(String filePath)                                                                                                                        
   {                                                                                                                                                                          
     String rootPath = systemParamsService.getSystemParamValueByCode(SystemParamsConstantsBase.param_code_attachment_path);                                                   
     rootPath = StringUtils.isEmpty(rootPath) ? "" : rootPath;                                                                                                                
     File file = new File(filePath);                                                                                                                                          
                                                                                                                                                                              
     if (!file.exists()) {                                                                                                                                                    
       filePath = rootPath + "/" + filePath;                                                                                                                                  
       file = new File(filePath);                                                                                                                                             
     }                                                                                                                                                                        
     if (!file.exists()) {                                                                                                                                                    
       return ResultCallback.fail("附件不存在! ");                                                                                                                                 
     }                                                                                                                                                                        
     return ResultCallback.success("附件存在 !");                                                                                                                                 
   }                                                                                                                                                                          
                                                                                                                                                                              
                                                                                                                                                                              
   @RequestMapping({"/checkFileExistById.do"})                                                                                                                                
   @ResponseBody                                                                                                                                                              
   public ResultCallback checkFileExistById(String attachmentId)                                                                                                              
   {                                                                                                                                                                          
     return attachmentService.checkFileExistById(attachmentId);                                                                                                               
   }                                                                                                                                                                          
                                                                                                                                                                              
                                                                                                                                                                              
                                                                                                                                                                              
   @RequestMapping({"/deleteAttachments.do"})                                                                                                                                 
   @ResponseBody                                                                                                                                                              
   public void deleteAttachments(String[] ids)                                                                                                                                
   {                                                                                                                                                                          
     attachmentService.deleteAttachments(ids);                                                                                                                                
   }                                                                                                                                                                          
 }                                                                                                                                                                            
          3.后端service代码

                                                                                                                            
@Component("attachmentService")                                                                                             
public class AttachmentService                                                                                              
  extends CommonService                                                                                                     
{                                                                                                                           
  private static final Logger log = Logger.getLogger(AttachmentService.class);                                              
                                                                                                                            
                                                                                                                            
                                                                                                                            
  @Autowired                                                                                                                
  @Resource                                                                                                                 
  protected SystemParamsService systemParamsService;                                                                        
                                                                                                                            
                                                                                                                            
  @Autowired                                                                                                                
  @Resource                                                                                                                 
  protected PmsEmployeeService pmsEmployeeService;                                                                          
                                                                                                                            
                                                                                                                            
                                                                                                                            
  private String createFile(MultipartFile file, String rootPath, String code, String filename)                              
  {                                                                                                                         
    String relativePath = "";                                                                                               
    String newDate = DateUtils.getNowDateStr1();                                                                            
    String newTime = DateUtils.getNowTimeNoRodStr();                                                                        
    try                                                                                                                     
    {                                                                                                                       
      String filePath = rootPath + "//" + code + "//" + newDate;                                                            
      File dir = new File(filePath);                                                                                        
                                                                                                                            
      if (!dir.exists()) {                                                                                                  
        dir.mkdirs();                                                                                                       
      }                                                                                                                     
                                                                                                                            
      File targetFile = new File(rootPath + "//" + code + "//" + newDate, newTime + "_" + filename);                        
                                                                                                                            
      if (!targetFile.exists()) {                                                                                           
        targetFile.createNewFile();                                                                                         
      }                                                                                                                     
      file.transferTo(targetFile);                                                                                          
      relativePath = "/" + code + "/" + newDate + "/" + newTime + "_" + filename;                                           
    } catch (Exception e) {                                                                                                 
      System.out.println(e.getMessage());                                                                                   
    }                                                                                                                       
    return relativePath;                                                                                                    
  }                                                                                                                         
                                                                                                                     
  public Object addFile(MultipartFile file, String code, UserSession userSession)                                           
  {                                                                                                                         
    Map<String, Object> resultMap = new HashMap();                                                                          
    Attachment attachment = null;                                                                                           
    try                                                                                                                     
    {                                                                                                                       
      String rootPath = systemParamsService.getSystemParamValueByCode(SystemParamsConstantsBase.param_code_attachment_path);
      rootPath = StringUtils.isEmpty(rootPath) ? "" : rootPath;                                                             
      if (StringUtils.isEmpty(rootPath)) {                                                                                  
        resultMap.put("success", Boolean.valueOf(false));                                                                   
        resultMap.put("result", "附件存储位置,未配置,请在附件管理页面配置!");                                                                  
        return resultMap;                                                                                                   
      }                                                                                                                     
      String filename = file.getOriginalFilename();                                                                         
                                                                                                                            
      String relativePath = createFile(file, rootPath, code, filename);                                                     
                                                                                                                            
                                                                                                                            
      attachment = new Attachment();                                                                                        
      attachment.setAttachmentId(CreateUuidUtil.getCreateUuid());                                                           
      attachment.setCode(code);                                                                                             
      attachment.setIsValid("1");                                                                                           
      attachment.setName(filename);                                                                                         
      attachment.setRelativePath(relativePath);                                                                             
      attachment.setUploadEmpId(userSession.getEmployeeCode());                                                             
      attachment.setUploadTime(DateUtils.getNowTimeStr());                                                                  
      attachment = (Attachment)commonDao.save(attachment);                                                                  
    } catch (Exception e) {                                                                                                 
      log.error("附件管理-附件上传出错:" + e.getMessage());                                                                           
      e.printStackTrace();                                                                                                  
      resultMap.put("success", Boolean.valueOf(false));                                                                     
      resultMap.put("result", "附件管理-附件上传出错:" + e.getMessage());                                                             
      return resultMap;                                                                                                     
    }                                                                                                                       
    resultMap.put("success", Boolean.valueOf(true));                                                                        
    resultMap.put("result", attachment);                                                                                    
                                                                                                                            
    return resultMap;                                                                                                       
  }                                                                                                                         
                                                                                                                  
  public ResultCallback deleteFile(UserSession userSession, String attachmentId)                                            
  {                                                                                                                         
    Attachment attachment = (Attachment)commonDao.get(Attachment.class, attachmentId);                                      
    attachment.setIsValid("0");                                                                                             
    attachment.setRmEmpId(userSession.getEmployeeCode());                                                                   
    attachment.setUpdateTime(DateUtils.getNowTimeStr());                                                                    
    commonDao.saveOrUpdate(attachment);                                                                                     
    return ResultCallback.success(null);                                                                                    
  }                                                                                                                         
                                                                                                                 
  public Page<Attachment> findAttachmentList(String serviceTableId, String code)                                            
  {                                                                                                                         
    Page<Attachment> page = new Page();                                                                                     
    page.setStartRecordIndex(0);                                                                                            
    page.setPageSize(CommonConstantsBase.exportExcelDataMaxRecords.intValue());                                             
    MyCriteria criteria = new MyCriteria(Attachment.class.getName());                                                       
    if (StringUtils.isNotBlank(serviceTableId)) {                                                                           
      criteria.addCondition(Conditions.eq("serviceTableId", serviceTableId));                                               
    }                                                                                                                       
    if (StringUtils.isNotBlank(code)) {                                                                                     
      criteria.addCondition(Conditions.eq("code", code));                                                                   
    }                                                                                                                       
    criteria.addCondition(Conditions.eq("isValid", "1"));                                                                   
    page = commonDao.findByMyCriteria(criteria, page);                                                                      
    return page;                                                                                                            
  }                                                                                                                         
                                                                                                       
  public ResultCallback saveUpdateServiceTableIds(List<String> attachmentIdList, String serviceTableId)                     
  {                                                                                                                         
    if ((attachmentIdList == null) || (StringUtils.isEmpty(serviceTableId))) {                                              
      return ResultCallback.fail("更新失败,关联表id为空或者没有要更新的附件!");                                                                
    }                                                                                                                       
    for (String attachmentId : attachmentIdList) {                                                                          
      if (StringUtils.isNotBlank(attachmentId)) {                                                                           
        Attachment attachment = (Attachment)commonDao.get(Attachment.class, attachmentId);                                  
        if (attachment != null) {                                                                                           
          attachment.setServiceTableId(serviceTableId);                                                                     
          commonDao.saveOrUpdate(attachment);                                                                               
        }                                                                                                                   
      }                                                                                                                     
    }                                                                                                                       
    return ResultCallback.success("绑定成功!");                                                                                 
  }                                                                                                                         
                                                                                                                    
  public ResultCallback saveUpdateServiceTableIdForOne(String attachmentId, String serviceTableId)                          
  {                                                                                                                         
    if ((StringUtils.isEmpty(attachmentId)) || (StringUtils.isEmpty(serviceTableId))) {                                     
      return ResultCallback.fail("更新失败,关联表id为空或者没有要更新的附件!");                                                                
    }                                                                                                                       
    Attachment attachment = (Attachment)commonDao.get(Attachment.class, attachmentId);                                      
    if (attachment != null) {                                                                                               
      attachment.setServiceTableId(serviceTableId);                                                                         
      commonDao.saveOrUpdate(attachment);                                                                                   
    }                                                                                                                       
                                                                                                                            
    return ResultCallback.success("绑定成功!");                                                                                 
  }                                                                                                                         
                                                                                                                                                                                                                                                                                                                                 
  public Page<AttachmentVo> findSystemAttachment(AttachmentVo attachmentVo)                                                 
  {                                                                                                                         
    Integer start = Integer.valueOf(attachmentVo.getStart());                                                               
    Integer limit = Integer.valueOf(attachmentVo.getLimit());                                                               
    Page<Attachment> page = new Page();                                                                                     
    page.setStartRecordIndex(start.intValue());                                                                             
    page.setPageSize(limit.intValue());                                                                                     
                                                                                                             
    MyCriteria criteria = new MyCriteria(Attachment.class.getName());                                                       
                                                                                                                            
    String code = attachmentVo.getCode();                                                                                   
    if (StringUtils.isNotEmpty(code)) {                                                                                     
      criteria.addCondition(Conditions.like("code", code));                                                                 
    }                                                                                                                       
                                                                                                                            
    String name = attachmentVo.getName();                                                                                   
    if (StringUtils.isNotEmpty(name)) {                                                                                     
      criteria.addCondition(Conditions.like("name", name));                                                                 
    }                                                                                                                       
                                                                                                                            
    String uploadTimeStart = attachmentVo.getUploadTimeStart();                                                             
    if (StringUtils.isNotEmpty(uploadTimeStart)) {                                                                          
      criteria.addCondition(Conditions.ge("uploadTime", DateFormateUtils.getDateStrNoRodWithFirstTime(uploadTimeStart))     
        .addLogicOr(Conditions.ge("uploadTime", uploadTimeStart)));                                                         
    }                                                                                                                       
                                                                                                                            
    String uploadTimeEnd = attachmentVo.getUploadTimeEnd();                                                                 
    if (StringUtils.isNotEmpty(uploadTimeEnd)) {                                                                            
      criteria.addCondition(Conditions.le("uploadTime", DateFormateUtils.getDateStrNoRodWithLastTime(uploadTimeEnd))        
        .addLogicOr(Conditions.le("uploadTime", uploadTimeEnd)));                                                           
    }                                                                                                                       
    criteria.addOrder(Order.desc("uploadTime"));                                                                            
    Page<Attachment> tmpPage = commonDao.findByMyCriteria(criteria, page);                                                  
    List<Attachment> systemAttachmentList = (List)tmpPage.getRecords();                                                     
    List<AttachmentVo> resultVoList = new ArrayList();                                                                      
    Page<AttachmentVo> resultPage = new Page();                                                                             
    if (systemAttachmentList != null) {                                                                                     
      for (Attachment systemAttachment : systemAttachmentList) {                                                            
        AttachmentVo vo = new AttachmentVo();                                                                               
        beanMapper.map(systemAttachment, vo);                                                                               
                                                                                                                            
        String uploadEmpName = pmsEmployeeService.getPmsEmpeNameByEmpeId(vo.getUploadEmpId());                              
        vo.setUploadEmpName(uploadEmpName);                                                                                 
                                                                                                                            
        resultVoList.add(vo);                                                                                               
      }                                                                                                                     
    }                                                                                                                       
                                                                                                                            
    resultPage.setPageSize(tmpPage.getPageSize());                                                                          
    resultPage.setRecords(resultVoList);                                                                                    
    resultPage.setStartRecordIndex(tmpPage.getStartRecordIndex());                                                          
    resultPage.setTotalCount(tmpPage.getTotalCount());                                                                      
                                                                                                                            
    return resultPage;                                                                                                      
  }                                                                                                                         
                                                                                                                   
  public void deleteAttachments(String[] ids)                                                                               
  {                                                                                                                         
    if (ids != null) { String[] arrayOfString;                                                                              
      int j = (arrayOfString = ids).length; for (int i = 0; i < j; i++) { String id = arrayOfString[i];                     
        Attachment attachment = (Attachment)commonDao.get(Attachment.class, id);                                            
        if (attachment != null) {                                                                                           
          attachment.setIsValid("0");                                                                                       
          commonDao.saveOrUpdate(attachment);                                                                               
        }                                                                                                                   
      }                                                                                                                     
    }                                                                                                                       
  }                                                                                                                         
                                                                                                                            
                                                                                                                            
  public Attachment getAttachmentById(String id)                                                                            
  {                                                                                                                         
    if (StringUtils.isEmpty(id)) {                                                                                          
      return null;                                                                                                          
    }                                                                                                                       
    return (Attachment)commonDao.get(Attachment.class, id);                                                                 
  }                                                                                                                         
                                                                                                                
  public String getAttachmentNameById(String id)                                                                            
  {                                                                                                                         
    Attachment attachment = getAttachmentById(id);                                                                          
    return attachment != null ? attachment.getName() : "";                                                                  
  }                                                                                                                         
                                                                                                      
  public ResultCallback checkFileExistById(String attachmentId)                                                             
  {                                                                                                                         
    Attachment attachment = getAttachmentById(attachmentId);                                                                
    String relativePath = attachment != null ? attachment.getRelativePath() : "";                                           
    if (StringUtils.isEmpty(relativePath)) {                                                                                
      return ResultCallback.fail("附件不存在! ");                                                                                
    }                                                                                                                       
                                                                                                                            
    String rootPath = systemParamsService.getSystemParamValueByCode(SystemParamsConstantsBase.param_code_attachment_path);  
    rootPath = StringUtils.isEmpty(rootPath) ? "" : rootPath;                                                               
    File file = new File(relativePath);                                                                                     
    String filePath = "";                                                                                                   
                                                                                                                            
    if (!file.exists()) {                                                                                                   
      filePath = rootPath + "/" + relativePath;                                                                             
      file = new File(filePath);                                                                                            
    }                                                                                                                       
    if (!file.exists()) {                                                                                                   
      return ResultCallback.fail("附件不存在! ");                                                                                
    }                                                                                                                       
    Map<String, Object> resultMap = new HashMap();                                                                          
    resultMap.put("filePath", relativePath);                                                                                
    resultMap.put("fileName", attachment.getName());                                                                        
                                                                                                                            
    return ResultCallback.success("附件存在 !", resultMap);                                                                     
  }                                                                                                                         
                           
  public String getFileCompletePathById(String attachmentId)                                                                
  {                                                                                                                         
    Attachment attachment = getAttachmentById(attachmentId);                                                                
    String relativePath = attachment != null ? attachment.getRelativePath() : "";                                           
    String filePath = "";                                                                                                   
    if (StringUtils.isNotEmpty(relativePath))                                                                               
    {                                                                                                                       
      String rootPath = systemParamsService.getSystemParamValueByCode(SystemParamsConstantsBase.param_code_attachment_path);
      rootPath = StringUtils.isEmpty(rootPath) ? "" : rootPath;                                                             
      File file = new File(relativePath);                                                                                   
                                                                                                                 
      if (!file.exists()) {                                                                                                 
        filePath = rootPath + "/" + relativePath;                                                                           
      } else {                                                                                                              
        filePath = relativePath;                                                                                            
      }                                                                                                                     
    }                                                                                                                       
                                                                                                                            
    return filePath;                                                                                                        
  }                                                                                                                         
}                                                                                                                                                                                                                                            

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值