Home Web Front-end Layui Tutorial layui+jfinal method to implement uploading

layui+jfinal method to implement uploading

Dec 05, 2019 pm 04:57 PM
layui

layui+jfinal method to implement uploading

layui + jfinal 实现上传下载:(推荐:layui使用教程

1、需要把jfinal的环境配置好

2、导入相关的库文件 

layui的库文件  

layui+jfinal method to implement uploading

就是这两个文件需要导入到自己的页面

JFinal 是基于Java 语言的极速 web 开发框架,其核心设计目标是开发迅速、代码量少、学习简单、功能强大、轻量级、易扩展、Restful。在拥有Java语言所有优势的同时再拥有ruby、python等动态语言的开发效率。

注意:jfinal总会把路径拦截,所以需要静态文件处理。本人不太懂。就网上找了下,说webRoot就是根目录,所以引入的时候,一定要在路径最开始加上 “/”

作为根目录路径。

layui+jfinal method to implement uploading

3、接下来就是前端和后台的编写了。

前端可以直接从layui的官网上查看相关文档,就是复制粘贴,改改就可以了

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>upload模块快速使用</title>
  <link rel="stylesheet" href="/assets/layui/css/layui.css" media="all">
</head>
<body>

 <div class="layui-upload">
  <button type="button" class="layui-btn" id="test1"><i class="layui-icon">&#xe67c;</i>上传图片</button>
  <div class="layui-upload-list">
    <img  class="layui-upload-img lazy"  src="/static/imghw/default1.png"  data-src="/assets/layui/layui.js"   id="demo1" alt="layui+jfinal method to implement uploading" >
    <p id="demoText"></p>
    <p id="yudu"></p>
    
  </div>
</div>
<p id="download"></p>
<script ></script>

<script>

layui.use(&#39;upload&#39;, function(){
  var $ = layui.jquery
  ,upload = layui.upload;
  
  //普通图片上传
  var uploadInst = upload.render({
    elem: &#39;#test1&#39;
    ,url: &#39;/hello/handleUpload&#39;
    ,before: function(obj){
      //预读本地文件示例,不支持ie8
      obj.preview(function(index, file, result){
        $(&#39;#demo1&#39;).attr(&#39;src&#39;, result); //图片链接(base64)
        console.log(index); //得到文件索引
        console.log(file); //得到文件对象
        //console.log(result); //得到文件base64编码,比如图片
        $("#yudu").html("<span>名字:"+file.name+"</span>"+"<span>大小:"+file.size+"</span>");
      });
    }
    ,done: function(res){
        //alert(res.code);
      //如果上传失败
      if(res.code > 0){
        return layer.msg(&#39;上传失败&#39;);
      }
      //上传成功
      layer.msg("上传成功");
      console.log(res.msg);
      $("#download").html("<a class=&#39;layui-btn layui-btn-small&#39; href=&#39;/hello/download?name="+res.msg+"&#39;>下载</a>");
    }
    ,error: function(){
      //演示失败状态,并实现重传
      var demoText = $(&#39;#demoText&#39;);
      demoText.html(&#39;<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>&#39;);
      demoText.find(&#39;.demo-reload&#39;).on(&#39;click&#39;, function(){
        uploadInst.upload();
      });
    }
  });
  
});
</script>
</body>
</html>
Copy after login

这是全部代码,如果比较懒的同学可以直接复制,这个和官网上的基本一样,只是路径做了修改,里边有几行注释调试的地方,可以删除的

4.最后就是后台控制器的代码

/**
     * 上传下载
     */
    public void upload(){
        render("/upload.html");
    }
    /**
     * 处理上传的东西,只有有方法就行。不用做处理就可以长传到默认的/upload 路径下
   * 这里可以自己做优化,修改,这里每次只能上传一个文件。本人随手就写成list了
     */
    public void handleUpload(){
    //这里是为了查看信息
       // List<UploadFile> files = getFiles();
    //补充,这样可以设置上传文件的路径,pact就是上传文件的路径,默认是在/update下,这是就是设置成了/update/pact/下,maxSize 设置文件每次上传的最大值
    List<UploadFile> pacts = getFiles("pact", maxSize);

        System.err.println(files.get(0).getFileName());
        System.err.println(files.get(0).getUploadPath());
        System.err.println(files.get(0).getOriginalFileName());
        System.err.println(files.get(0).getContentType());
        System.err.println(files.get(0).getParameterName());
    //这里为了在页面上做下载所以就需要把文件上传到服务器的名字传过去,用作下载时候调用,找到指定的文件
        setAttr("msg",files.get(0).getFileName());
        renderJson();
    }
    
    /**
     * 下载
     */
    public void download(){
    //查看传过来的文件名字,测试用
       // String para = getPara("name");
       // System.err.println(para);
    //拿到下载文件所在的服务器路径
          String fpath = getSession().getServletContext().getRealPath("/upload");  
    //服务器路径和文件路径拼接
          File file=new File(fpath+"/"+para);  
        //判断文件是否存在,存在就把文件传到前端下载
           if(file.exists()){  
            renderFile(file);         
           }  
           else{  
                renderJson();  
          }  
    }

这样基本就没什么了,写完了。

注意这里可能会报一个错误


[ERROR]-[Thread: qtp817406040-23]-[com.jfinal.core.ActionHandler.handle()]: /hello/handleUpload
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.jfinal.aop.Invocation.invoke(Invocation.java:87)
    at com.jfinal.core.ActionHandler.handle(ActionHandler.java:74)
    at com.jfinal.core.JFinalFilter.doFilter(JFinalFilter.java:73)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1307)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:453)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:560)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1072)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:382)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1006)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:365)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:485)
    at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:937)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:998)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:856)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:628)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.jfinal.aop.Invocation.invoke(Invocation.java:73)
    ... 25 more
Caused by: java.lang.NoClassDefFoundError: com/oreilly/servlet/multipart/FileRenamePolicy
    at com.jfinal.core.Controller.getFiles(Controller.java:775)
    at com.rjj.control.StudentControl.handleUpload(StudentControl.java:235)
    ... 30 more
Caused by: java.lang.ClassNotFoundException: com.oreilly.servlet.multipart.FileRenamePolicy
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:430)
    at com.jfinal.server.JFinalClassLoader.loadClass(JFinalClassLoader.java:53)
    ... 32 more
Copy after login

这个问题是因为少一个jar包,只要把响应的jar导入就可以解决了。

The above is the detailed content of layui+jfinal method to implement uploading. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set up jump on layui login page How to set up jump on layui login page Apr 04, 2024 am 03:12 AM

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

How to get form data in layui How to get form data in layui Apr 04, 2024 am 03:39 AM

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

How layui implements self-adaptation How layui implements self-adaptation Apr 26, 2024 am 03:00 AM

Adaptive layout can be achieved by using the responsive layout function of the layui framework. The steps include: referencing the layui framework. Define an adaptive layout container and set the layui-container class. Use responsive breakpoints (xs/sm/md/lg) to hide elements under specific breakpoints. Specify element width using the grid system (layui-col-). Create spacing via offset (layui-offset-). Use responsive utilities (layui-invisible/show/block/inline) to control the visibility of elements and how they appear.

How to transfer data in layui How to transfer data in layui Apr 26, 2024 am 03:39 AM

The method of using layui to transmit data is as follows: Use Ajax: Create the request object, set the request parameters (URL, method, data), and process the response. Use built-in methods: Simplify data transfer using built-in methods such as $.post, $.get, $.postJSON, or $.getJSON.

What is the difference between layui and vue? What is the difference between layui and vue? Apr 04, 2024 am 03:54 AM

The difference between layui and Vue is mainly reflected in functions and concerns. Layui focuses on rapid development of UI elements and provides prefabricated components to simplify page construction; Vue is a full-stack framework that focuses on data binding, component development and state management, and is more suitable for building complex applications. Layui is easy to learn and suitable for quickly building pages; Vue has a steep learning curve but helps build scalable and easy-to-maintain applications. Depending on the project needs and developer skill level, the appropriate framework can be selected.

How to run layui How to run layui Apr 04, 2024 am 03:42 AM

To run layui, perform the following steps: 1. Import layui script; 2. Initialize layui; 3. Use layui components; 4. Import layui styles (optional); 5. Ensure script compatibility and pay attention to other considerations. With these steps, you can build web applications using the power of layui.

What does layui mean? What does layui mean? Apr 04, 2024 am 04:33 AM

layui is a front-end UI framework that provides a wealth of UI components, tools and functions to help developers quickly build modern, responsive and interactive web applications. Its features include: flexible and lightweight, modular design, rich components, Powerful tools and easy customization. It is widely used in the development of various web applications, including management systems, e-commerce platforms, content management systems, social networks and mobile applications.

What language is layui framework? What language is layui framework? Apr 04, 2024 am 04:39 AM

The layui framework is a JavaScript-based front-end framework that provides a set of easy-to-use UI components and tools to help developers quickly build responsive web applications. Its features include: modular, lightweight, responsive, and has complete documentation and community support. layui is widely used in the development of management backend systems, e-commerce websites, and mobile applications. The advantages are quick start-up, improved efficiency, and easy maintenance. The disadvantages are poor customization and slow technology updates.

See all articles