博客
关于我
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/

你可能感兴趣的文章
Necurs僵尸网络攻击美国金融机构 利用Trickbot银行木马窃取账户信息和欺诈
查看>>
Needle in a haystack: efficient storage of billions of photos 【转】
查看>>
NeHe OpenGL教程 07 纹理过滤、应用光照
查看>>
NeHe OpenGL教程 第四十四课:3D光晕
查看>>
Neighbor2Neighbor 开源项目教程
查看>>
neo4j图形数据库Java应用
查看>>
Neo4j图数据库_web页面关闭登录实现免登陆访问_常用的cypher语句_删除_查询_创建关系图谱---Neo4j图数据库工作笔记0013
查看>>
Neo4j图数据库的介绍_图数据库结构_节点_关系_属性_数据---Neo4j图数据库工作笔记0001
查看>>
Neo4j图数据库的数据模型_包括节点_属性_数据_关系---Neo4j图数据库工作笔记0002
查看>>
Neo4j安装部署及使用
查看>>
Neo4j电影关系图Cypher
查看>>
Neo4j的安装与使用
查看>>
Neo4j(1):图数据库Neo4j介绍
查看>>
Neo4j(2):环境搭建
查看>>
Neo4j(3):Neo4j Desktop安装
查看>>
Neo4j(4):Neo4j - CQL使用
查看>>
Neo图数据库与python交互
查看>>
NEO改进协议提案1(NEP-1)
查看>>
Neo私链
查看>>
NervanaGPU 项目使用教程
查看>>