• 使用layui进行文件上传


    今天进行了layui文件上传,也是我的大作业的第一阶段;

    要求:多个文件导入,生成数据字典csv exl自动提表头 两列英文字段按英文名称排序  数据导入  公式编辑表间关联关系主界面

    今天处理的是多个文件的导入:网上查找的layui的代码

    首先是html界面,

    <div class="layui-body" >
    <div class="UpFileDivd" align="center">
    <div class="layui-upload-drag" id="test10">
    <i class="layui-icon"></i>
    <p>点击上传,或将文件拖拽到此处</p>
    <div class="layui-hide" id="uploadDemoView">
    <hr>
    <img src="" alt="上传成功后渲染" style="max- 196px">
    </div>
    </div>
    </br></br>
    <button id="UpBtn" class="layui-btn" >上传</button>
    </div>
    <div class="UpTable">
    <div class="layui-upload-list" style="max- 1000px;">
    <table class="layui-table">
    <colgroup>
    <col width="400">
    <col width="150">
    <col width="260">
    <col width="150">
    </colgroup>
    <thead>
    <tr><th>文件名</th>
    <th>大小</th>
    <th>上传进度</th>
    <th>操作</th>
    </tr></thead>
    <tbody id="demoList"></tbody>
    </table>
    </div>
    </div>
    </div>
    然后是script部分
    <script>
    layui.use(['upload', 'element', 'layer'], function(){
    var $ = layui.jquery
    ,upload = layui.upload
    ,element = layui.element
    ,layer = layui.layer;
    upload.render({
    elem: '#test10'
    ,elemList: $('#demoList')
    ,accept: 'file'
    ,auto: false
    ,bindAction:'#UpBtn'
    ,url: 'servlet?method=tecon' //此处用的是第三方的 http 请求演示,实际使用时改成您自己的上传接口即可。
    ,done: function(res){
    },choose: function(obj){
    var that = this;
    var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
    //读取本地文件
    obj.preview(function(index, file, result){
    var strlist=file.name.split('.')
    if(strlist[strlist.length-1]!="xlsx"&&strlist[strlist.length-1]!="csv"){
    layer.alert('上传文件错误,上传xlsx或csv', function(index){
    //do something

    layer.close(index);
    });
    delete files[index];
    }
    else {
    var tr = $(['<tr id="upload-'+ index +'">'
    ,'<td>'+ file.name +'</td>'
    ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
    ,'<td><div class="layui-progress" lay-filter="progress-demo-'+ index +'"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
    ,'<td>'
    ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
    ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
    ,'</td>'
    ,'</tr>'].join(''));
    }
    //单个重传
    tr.find('.demo-reload').on('click', function(){
    obj.upload(index, file);
    });

    //删除
    tr.find('.demo-delete').on('click', function(){
    delete files[index]; //删除对应的文件
    tr.remove();
    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
    });

    that.elemList.append(tr);
    element.render('progress'); //渲染新加的进度条组件
    });
    }
    ,done: function(res, index, upload){ //成功的回调
    var that = this;
    //if(res.code == 0){ //上传成功
    var tr = that.elemList.find('tr#upload-'+ index)
    ,tds = tr.children();
    tds.eq(3).html(''); //清空操作
    delete this.files[index]; //删除文件队列已经上传成功的文件
    return;
    //}
    this.error(index, upload);
    }
    ,allDone: function(obj){ //多文件上传完毕后的状态回调
    console.log(obj)
    }
    ,error: function(index, upload){ //错误回调
    var that = this;
    var tr = that.elemList.find('tr#upload-'+ index)
    ,tds = tr.children();
    tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
    ,progress: function(n, elem, e, index){ //注意:index 参数为 layui 2.6.6 新增
    element.progress('progress-demo-'+ index, n + '%'); //执行进度条。n 即为返回的进度百分比
    }

    });
    });
    </script>
    效果:

     然后是Java代码部分:

    public void tecon( HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, SQLException, InterruptedException {
    if (!ServletFileUpload.isMultipartContent(request)) {
    // 如果不是则停止
    PrintWriter writer = response.getWriter();
    writer.println("Error: 表单必须包含 enctype=multipart/form-data");
    writer.flush();
    return;
    }
    String fileName="";
    String filePath="";
    // 配置上传参数
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // 设置临时存储目录
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // 设置最大文件上传值
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // 设置最大请求值 (包含文件和表单数据)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // 中文处理
    upload.setHeaderEncoding("UTF-8");

    // 构造临时路径来存储上传的文件
    // 这个路径相对当前应用的目录
    String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;


    // 如果目录不存在则创建
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
    uploadDir.mkdir();
    }

    try {
    // 解析请求的内容提取文件数据
    @SuppressWarnings("unchecked")

    List<FileItem> formItems = upload.parseRequest(request);

    if (formItems != null && formItems.size() > 0) {
    // 迭代表单数据
    for (FileItem item : formItems) {
    // 处理不在表单中的字段
    if (!item.isFormField()) {
    fileName= new File(item.getName()).getName();
    filePath = uploadPath + File.separator + fileName;
    File storeFile = new File(filePath);
    // 在控制台输出文件的上传路径
    System.out.println(filePath);
    // 保存文件到硬盘
    item.write(storeFile);
    request.setAttribute("message",
    "文件上传成功!");
    }
    }
    }
    } catch (Exception ex) {
    request.setAttribute("message",
    "错误信息: " + ex.getMessage());
    }
    HttpSession session = request.getSession();
    String id=(String) session.getAttribute("id");
    char[] nameArr=fileName.toCharArray();
    String filename="";
    for (int i = 0; i < nameArr.length; i++) {
    if(nameArr[i]!='('&&nameArr[i]!=')'&&nameArr[i]!='-'&&nameArr[i]!='、')filename=filename+nameArr[i];
    }
    String[] spstr=filename.split("\\.");

    StringBuffer strbuff = new StringBuffer();
    System.out.println(spstr.length);
    for (int i = 0; i < spstr.length-1; i++) {
    strbuff.append(spstr[i]);
    }
    String TableName=strbuff.toString();
    dao.CreataTab(TableName);
    ReadExcel r=new ReadExcel();
    List<List<Object>> rowlist=r.ExcelToRowList(filePath);
    dao.FirInputData(rowlist,TableName);
    dao.FirInsertToHis(TableName,id);
    JSONObject ob=new JSONObject();
    ob.put("code", 0);
    ob.put("msg", "");
    ob.put("count",1);
    ob.put("data","'filename':'AAA'");
    PrintWriter out = response.getWriter();
    out.write(ob.toString());
    }
    这样就可以做到多个文件的导入了。
     
  • 相关阅读:
    关于基本的线程的生命周期
    HTML Response ContentType 大全
    IE与Firefox的CSS兼容大全
    文件上传代码
    C#.NET里面抽象类和接口有什么区别
    用SQL命令创建数据库
    JS根据生日算岁数
    改变Iframe的Src
    JS做加法精度问题
    真正的问题应该在我身上……
  • 原文地址:https://www.cnblogs.com/092e/p/15526103.html
Copyright © 2020-2023  润新知