上篇文件是本地的一个文件,但实际需求是,从本地上传一个文件,并导入excel入数据库。

页面效果是

html主要代码是:

                <div class="form-group" style="top:-5px;left:360px;width:1000px;">
                                <div class="col-sm-12">
                                    <div data-provides="fileupload" class="fileupload fileupload-new"><input type="hidden">
                                        <span class="btn btn-file btn-light-grey"><i class="fa fa-folder-open-o"></i> <span class="fileupload-new">上传家属会见</span><span class="fileupload-exists">更换文件</span>
                                            <input type="file" name="importJsfile" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
                                        </span>
                                        <span class="fileupload-preview"></span>
                                        <a data-dismiss="fileupload" class="close fileupload-exists float-none" href="#">
                                            ×
                                        </a>
                                    </div> 
                                </div>
                         </div> 

 

是bootstrap的ui,重点:

accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"

加入可在选择文件时候只选择excel格式。
后台:

private static String UPLOADPATH = "/files/aq/hj/js/";     //上传文件的路径

/**
         * 导入家属会见保存
         * @throws IOException 
         */
        public void save_importJs() throws IOException{
            Boolean bool = false;
            //获取上传文件
            String realPath = super.getRealPath();
            //获取上传的图片
            String uploadPath = realPath + UPLOADPATH;
            UploadFile rymdfile = getFile("importJsfile",uploadPath);   //方法第一个参数的name值是  Input type='file' 的name值
            
            if (rymdfile != null) {
                String filePath = rymdfile.getSaveDirectory() + rymdfile.getFileName();
                Record  record =new Record();
                String name =rymdfile.getFileName();
                System.out.println("文件名是"+name);
                FileInputStream  f = new FileInputStream(new File(filePath));
                record     = readXls(f,name);              //调用(上篇)中方法结果,将刚刚上传的excel导入数据库
        
if(record.get("list") != null ) { List<Hjrxx> hjrxxList = record.get("hjrxxList"); List<Hj> hjList = record.get("list"); bool = HjService.service.saveJsxx(hjrxxList,hjList); } }; renderText(String.valueOf(bool)); }