博客
关于我
bootstrap+springMvc 文件上传
阅读量:120 次
发布时间:2019-02-26

本文共 4834 字,大约阅读时间需要 16 分钟。

1、首先导入要用的js库

2、在xml配置

3.jsp页面

                                <button id="impExcelBtn" type="button" class="btn btn-primary">

                                <span class="fa fa-file-excel-o fa-fw"></span>导入</button>

上传文件框

    <div class="modal fade" id="ImpModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop='static'>

        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="impFile">导入Excel名单</h4>
                </div>
                <div class="modal-body">
                    <form class="impExcelPath form-horizontal">
                        <div class="form-group">
                            <label class="col-xs-2 control-label">文件路径</label>
                            <div class="col-sm-9">
                                 <input type="file" id="excelfile" name="file" />
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default btn-sm"
                        data-dismiss="modal">
                        <i class="fa fa-close fa-fw"></i> &ensp;关闭
                    </button>
                </div>
            </div>
        </div>
    </div>

js中代码

$('#excelfile').fileinput({

    uploadUrl: 'flowUpload.do?tradeCode=200403&formCode=QZ100103',
    msgPlaceholder: '请选择一个文件...',
    enctype: 'multipart/form-data',
    uploadAsync: false,
    showCancel: false,
    showUpload: true,
    showRemove: false,
    showCaption: true,
    showPreview: false,
    dropZoneEnabled: false,
    autoReplace: true,
    maxFileCount: 1,
    validateInitialCount: true,
    allowedFileExtensions: ['xlsx', 'xls'],
    language: 'zh'
}).on('filebatchuploadsuccess',    function(event, data, previewId, index) {
    $('#ImpModal').modal('hide');
    $(event.target).fileinput('clear').fileinput('unlock');
    alertMsg(data.response.msg);
}).on('filebatchuploaderror',    function(event, data, previewId, index) {
    $('#ImpModal').modal('hide');
    $("#excelfile").fileinput('clear').fileinput('unlock');
    alertMsg(data.response.msg);
});

$('#impExcelBtn').on('click',    function() {

    $(".fileinput-remove-button").click();
    $('#ImpModal .modal-title').html('导入Excel名单');
    $("#excelfile").fileinput('clear').fileinput('unlock');
    $('#ImpModal').modal();
});

JAVA 后台

    @RequestMapping("/flowUpload.do")

    public ModelAndView flowUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        Map<String,Object> result= new HashMap<String, Object>();
        // 转型为MultipartHttpRequest:
        MultipartHttpServletRequest multipartRequest = null;
        if (request instanceof MultipartHttpServletRequest) {
            multipartRequest = (MultipartHttpServletRequest)(request);
            // 获得文件:
            MultipartFile file= multipartRequest.getFile("file");
        //    System.out.println("uploadfilePath:"+uploadfilePath);
            
            String uploadfilePath = request.getSession().getServletContext().getRealPath("/uploadFile/");//获取项目路径+上传文件夹
            String fileName = file.getOriginalFilename();   //获取文件名称带后缀
            System.out.println("-路径-:"+uploadfilePath+"--文件名:"+fileName);
            File myPath = new File( uploadfilePath);  
            if ( !myPath.exists()){//若此目录不存在,则创建之  
                myPath.mkdir();  
                System.out.println("创建文件夹路径为:"+ uploadfilePath);  
            }  
            
            try{
                if(!(file.getOriginalFilename() == null || "".equals(file.getOriginalFilename()))){
                    // 对文件进行存储处理
                    FileOutputStream fs=new FileOutputStream( uploadfilePath + File.separator+ file.getOriginalFilename());

                    System.out.println("------------"+uploadfilePath + File.separator+ file.getOriginalFilename());

                    int len = file.getInputStream().available();
                    logger.info("文件大小"+len);
                    byte[] buffer = null;
                    if(len != 0){
                        buffer = new byte[len];
                    }else
                    {
                        buffer = new byte[1024*1024];
                    }
                    int bytesum = 0;
                    int byteread = 0;
                    InputStream inputStream = file.getInputStream();
                    while ((byteread=inputStream.read(buffer))!=-1)
                    {
                        bytesum+=byteread;
                        fs.write(buffer,0,byteread);
                        fs.flush();
                    }
                    fs.close();
                    file.getInputStream().close();
     
                    
                    Map model = new HashMap();
                    Map params = new HashMap();
                    Map body = new HashMap();
                    PubMethod.Request2Map(request, params);
                    String formcode = (String) params.get("formCode");
                    String tradecode = (String) params.get("tradeCode");
                    body.put("teller_code", "");
                    //body.put("uploadfilePath", uploadfilePath);
                    BDPReq reqMap = PubMethod.CreateBDPReq(request, Constants.APP_CODE, tradecode, formcode, body);
                    reqMap.setFN(fileName);
                    reqMap.setFLP(Tools.getPlatConfig("FTP_FILEPATH"));
                    BDPRsp rsp = PubMethod.SendAndRecvBDPMsg(reqMap);
                    if(rsp != null){
                        body = rsp.getBody();
                        BDPRspHead head = rsp.getHead();
                        System.out.println("响应报文body:"+ JSONObject.fromObject(body));
                        System.out.println("响应报文head:"+head);
                        if(Constants.BDP_SUCCESS_CODE.equals(head.getMsgcode())){
                            result.put("success", "true");
                            result.put("msg", "成功!");
                            /*model.put("total", body.get("total"));  
                            model.put("rows", body.get("rows"));*/
                        }else{
                            model.put("success", "false");
                            throw new BusinessException("W0000-0027", head.getMsgtxt());
                        }
                        
                    }else{
                        throw new BusinessException("W0000-0027", "交易异常!");
                    }
                }
            }catch(IOException e){
                result.put("msg","出错了");
                result.put("success","false");
                e.printStackTrace();
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
        return new ModelAndView("jsonView", result);
    }

 

转载地址:http://tssu.baihongyu.com/

你可能感兴趣的文章
mabatis 中出现&lt; 以及&gt; 代表什么意思?
查看>>
Mac book pro打开docker出现The data couldn’t be read because it is missing
查看>>
MAC M1大数据0-1成神篇-25 hadoop高可用搭建
查看>>
mac mysql 进程_Mac平台下启动MySQL到完全终止MySQL----终端八步走
查看>>
Mac OS 12.0.1 如何安装柯美287打印机驱动,刷卡打印
查看>>
MangoDB4.0版本的安装与配置
查看>>
Manjaro 24.1 “Xahea” 发布!具有 KDE Plasma 6.1.5、GNOME 46 和最新的内核增强功能
查看>>
mapping文件目录生成修改
查看>>
MapReduce程序依赖的jar包
查看>>
mariadb multi-source replication(mariadb多主复制)
查看>>
MariaDB的简单使用
查看>>
MaterialForm对tab页进行隐藏
查看>>
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>
memset初始化高维数组为-1/0
查看>>
Metasploit CGI网关接口渗透测试实战
查看>>
Metasploit Web服务器渗透测试实战
查看>>