zoukankan      html  css  js  c++  java
  • extjs插件开发上传下载文件简单案例

    前台,extjs,框架,mybatis,spring,springMVC,简单的文件上传下载案例。

    必要的jar包,commons-fileupload-1.3.1.jar,commons-io-2.0.1.jar,commons-lang-2.6.jar

    1、extjs前台,文件上传:

    上传window。

    Ext.ns('Ext.sms')
    Ext.sms.BaseRulesUploadWindow=Ext.extend(Ext.Window,{
        constructor:function(_config){   
            if(_config==null){        
                _config={};
            }
            Ext.apply(this,_config);    
            this.uploadPanel=new Ext.FormPanel({
                    fileUpload : true, //默认为图片上传
                    id:Ext.id(),
                    
                    baseCls : 'x-plain',
                    bodyStyle : 'padding-top:10px;padding-left:0px;',
                    closealbe : true,
                    items : [{
                            labeWidth:40,
                            xtype : 'textfield',
                            name : 'file',
                            inputType : 'file',
                            allowBlank : false,
                            160,
                            fieldLabel : '上传'
                    }]
            });
            Ext.sms.BaseRulesUploadWindow.superclass.constructor.call(this,{
                title:'文件上传',
                id:Ext.id(),
                modal:true,
                height:120,
                350,
                items:[this.uploadPanel]
            });
        }
    });

    2、上传的controller方法:

        /**
         * 方法描述:上传文件到本地
         * @param file 要上传的文件
         * @param request
         * @param response 写出
         */
        @RequestMapping("/upload")
        public void upload(@RequestParam MultipartFile file,HttpServletRequest request,HttpServletResponse response){
            try {
                String msg = FileDownLoadUtils.fileUpload(file, request, "/upload/baseRules", 0);
                System.out.println(msg);
                response.setContentType("text/html;charset=utf-8;");
                response.getWriter().write(msg);
                response.getWriter().flush();
                response.getWriter().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    3、静态的文件上传方法:(本方法属于FileDownLoadUtils类)

    public static String fileUpload(MultipartFile file, HttpServletRequest request,String saveFolder,long maxSize){
            String returnMsg  = null;
            try {
                
                // 保存的地址
                String savePath = request.getSession().getServletContext().getRealPath("/"+saveFolder);
                if(maxSize!=0 && file.getSize()>maxSize){
                    returnMsg = JackJson.fromObjectToJson(new ExtReturn(false, "文件大小超过了"+maxSize/(1024*1024)+"M了,上传失败!"));
                    return returnMsg;
                }
                // 上传的文件名 //需要保存
                String uploadFileName = file.getOriginalFilename();
                // 获取文件后缀名 //需要保存
                String fileType = StringUtils.substringAfterLast(uploadFileName, ".");
                // 以年月/天的格式来存放
                String dataPath = DateFormatUtils.format(new Date(), "yyyy-MM" + File.separator + "dd");
                // uuid来保存不会重复
                String saveName = UUID.randomUUID().toString().replace("-", "");
                // 最终相对于upload的路径,解决没有后缀名的文件 //需要保存
                // 为了安全,不要加入后缀名
                // 2011-1218364b45f-244d-41b6-bbf4-8df32064a935,等下载的的时候在加入后缀名
                String finalPath = File.separator + dataPath + File.separator + saveName + ("".equals(fileType) ? "" : "." + fileType);
                logger.debug("savePath:{},finalPath:{}", new Object[] { savePath, finalPath });
                File saveFile = new File(savePath + finalPath);
                // 判断文件夹是否存在,不存在则创建
                if (!saveFile.getParentFile().exists()) {
                    saveFile.getParentFile().mkdirs();
                }
                // 写入文件
                FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
                // 保存文件的基本信息到数据库
                StringBuffer buffer = new StringBuffer();
                buffer.append("{success:true,fileInfo:{fileName:'").append(uploadFileName).append("',");
                buffer.append("filePath:'").append(savePath.replace("\", "/")+finalPath.replace("\", "/")).append("',");          
                buffer.append("projectPath:'").append(saveFolder).append(finalPath.replace("\", "/")).append("',");
                buffer.append("storeName:'").append(saveName + ("".equals(fileType) ? "" : "." + fileType));
                buffer.append("'}}");
                returnMsg = buffer.toString();
                
            } catch (Exception e) {
                logger.error("Exception: ", e);
            }
            return returnMsg;
        }

    4、spring-servlet.xml文件中需要配置multipartfile相关的配置:如下

    <init-param>
    <param-name>upload.enabled</param-name>
    <param-value>false</param-value>
    </init-param>

    《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《

    1、文件下载

    基于XTemplate白板的文件下载extjs页面

    Ext.ns('Ext.sms')
    Ext.sms.BaseRulesReadWindow = new Ext.extend(Ext.Window,{
        downloadUrl:ctx+"/baseRulesFile/downLoadFile",
        constructor:function(_config){
            if(_config==null){
                _config={};
            }

            Ext.apply(this,_config);
            Ext.sms.BaseRulesReadWindow.superclass.constructor.call(this,{
                720,
                height:480,
                bodyStyle: 'background:white;',
                layout:'fit',
                autoScroll:true,
                modal:true, // 模态窗口
                closeAction:'hide',
                closable:true,
                padding:'5 5 5 5',
                buttons:[{
                    text:'关闭',
                    scope:this,
                    handler:function(){
                        this.hide();
                    }
                }]
                
            });
        },
        afterRender:function(){
            Ext.sms.BaseRulesReadWindow.superclass.afterRender.call(this);
            this.initTemplate();
        },
        initTemplate: function(){
            this.noticeTemplate = new Ext.XTemplate('<div class="notice">',
                '<div style="text-align:center;font-size: 200%;<h2>{rulesTitle}</h2></div>',
                '<div style="text-align:right;padding-right:0.5cm;font-size: 110%;background-color:white"><span>作者:{rulesAuthor}</span>&nbsp;&nbsp;<span>创建时间:{createTime:date("Y-m-d H:i:s")}</span></div>',
                '<div style="text-indent:20px;padding: 0.5cm;line-height:150%;font-size: 130%;{rulesContent}</div>',
                '<tpl if="fileList != null">',
                '<div style="text-indent:20px;padding: 0.5cm;line-height:150%;font-size: 120%;<ul>',            
                '<tpl for="fileList">',    
                   '<tpl if="downloadPath != null">',
                       '<li id="li-{[values.fileId]}">附件名称:<a class="noticeFile" href="{[values.downloadPath]}?filePath={[values.filePath]}&fileName={[values.fileName]}&id={[parent.id]}&attachId={[values.fileID]}" target="_self">{[values.fileName]}</a>&nbsp;&nbsp;</li>',            
                   '</tpl>',
                   '<tpl if="downloadPath == null">',
                       '<li id="li-{[values.fileId]}">附件名称:<a class="noticeFile" href="'+this.downloadUrl+'?fileId={[values.fileId]}" target="_self">{[values.fileName]}</a>&nbsp;&nbsp;</li>',            
                   '</tpl>',
                '</tpl>',                
                '</ul></div>',
                '</tpl>',
                '</div>'
            );        
            this.noticeTemplate.compile();
        },
        loadBaseRules:function(notice){
            if(notice==null){
                notice={};
            }
            this.noticeTemplate.overwrite(this.body,notice);
        }
    })

    2、文件下载controller

    /**
         * 方法描述:下载文件
         * @param fileId 要下载的文件,唯一标识
         * @param session
         * @param response
         */
        @RequestMapping(value="/downLoadFile", method = RequestMethod.GET)
        public void downLoadFile(String fileId,HttpSession session,HttpServletResponse response){
                //获取文件详细信息
                BaseRulesFile baseRulesFile = baseRulesFileService.getFileById(fileId);
                // 下载
                String filePath = session.getServletContext().getRealPath("/");
                //下载
                FileDownLoadUtils.downloadFile(baseRulesFile.getFilePath(), baseRulesFile.getFileName(), response);       
            }

    3、静态的文件下载方法:(本方法属于FileDownLoadUtils类)

    public static void  downloadFile(String filePath,String fileName,HttpServletResponse response){
            InputStream input = null;
            ServletOutputStream output = null;
            try {
                File downloadFile = new File(filePath);
                // 判断文件夹是否存在,不存在则创建
                if (!downloadFile.getParentFile().exists()) {
                    downloadFile.getParentFile().mkdirs();
                }
                // 判断是否存在这个文件
                if (!downloadFile.isFile()) {
                    // 创建一个
                    FileUtils.touch(downloadFile);
                }           
            
                //response.setContentType("application/octet-stream;charset=UTF-8");
                response.setContentType("application/x-msdownload");  
                response.setCharacterEncoding("UTF-8");
               
    //            response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
              //解决中文乱码  
                response.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("gbk"),"iso-8859-1"));  

                input = new FileInputStream(downloadFile);
                output = response.getOutputStream();
                IOUtils.copy(input, output);
                output.flush();
            } catch (Exception e) {
                logger.error("Exception: ", e);
            } finally {
                IOUtils.closeQuietly(output);
                IOUtils.closeQuietly(input);
            }
        }

    4、spring-servlet.xml文件中需要配置multipartfile相关的配置:如下

    <init-param>
    <param-name>upload.enabled</param-name>
    <param-value>false</param-value>
    </init-param>
     

    //以上是简单的文件上传下载重点环节

  • 相关阅读:
    Java实现 计蒜客 拯救行动
    Java实现 计蒜客 拯救行动
    Java实现 LeetCode 174 地下城游戏
    Java实现 LeetCode 174 地下城游戏
    Java实现 LeetCode 174 地下城游戏
    Java实现 LeetCode 173 二叉搜索树迭代器
    Java实现 LeetCode 173 二叉搜索树迭代器
    Visual Studio的SDK配置
    怎样使用CMenu类
    mfc menu用法一
  • 原文地址:https://www.cnblogs.com/zrui-xyu/p/4633296.html
Copyright © 2011-2022 走看看