search
HomeWeb Front-endLayui Tutoriallayui+jfinal method to implement uploading

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/imghwm/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>

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

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

这个问题是因为少一个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
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How do I use Layui's flow module for infinite scrolling?How do I use Layui's flow module for infinite scrolling?Mar 18, 2025 pm 01:01 PM

The article discusses using Layui's flow module for infinite scrolling, covering setup, best practices, performance optimization, and customization for enhanced user experience.

How do I use Layui's element module to create tabs, accordions, and progress bars?How do I use Layui's element module to create tabs, accordions, and progress bars?Mar 18, 2025 pm 01:00 PM

The article details how to use Layui's element module to create and customize UI elements like tabs, accordions, and progress bars, highlighting HTML structures, initialization, and common pitfalls to avoid.Character count: 159

How do I customize the appearance and behavior of Layui's carousel module?How do I customize the appearance and behavior of Layui's carousel module?Mar 18, 2025 pm 12:59 PM

The article discusses customizing Layui's carousel module, focusing on CSS and JavaScript modifications for appearance and behavior, including transition effects, autoplay settings, and adding custom navigation controls.

How do I use Layui's carousel module to create image sliders?How do I use Layui's carousel module to create image sliders?Mar 18, 2025 pm 12:58 PM

The article guides on using Layui's carousel module for image sliders, detailing steps for setup, customization options, implementing autoplay and navigation, and performance optimization strategies.

How do I configure Layui's upload module to restrict file types and sizes?How do I configure Layui's upload module to restrict file types and sizes?Mar 18, 2025 pm 12:57 PM

The article discusses configuring Layui's upload module to restrict file types and sizes using accept, exts, and size properties, and customizing error messages for violations.

How do I use Layui's layer module to create modal windows and dialog boxes?How do I use Layui's layer module to create modal windows and dialog boxes?Mar 18, 2025 pm 12:46 PM

The article explains how to use Layui's layer module to create modal windows and dialog boxes, detailing setup, types, customization, and common pitfalls to avoid.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.