bootstrap+springMvc 文件上傳

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);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章