springboot+layui实现文件上传(带进度条)

1.目录结构
springboot+layui实现文件上传(带进度条)_第1张图片

2.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ljc</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.uploadPage.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="layui/css/layui.css" media="all">
    <script src="layui/layui.js"></script>
</head>
<body>
<button type="button" class="layui-btn" id="addFile">
    <i class="layui-icon">&#xe67c;</i>添加文件
</button>
<button type="button" class="layui-btn" id="upload">上传</button>
<div class="layui-upload-list">
    <img style="width: 400px;height: 400px" id="demo1">
</div>
<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="uploadProgressBar">
    <div class="layui-progress-bar" lay-percent="0%"></div>
</div>
</body>
<script>
    layui.use(["layer","form", "upload","jquery","element"], function () {
        // 注意:为了动态显示进度条,必须加载element组件
        var layer = layui.layer, upload = layui.upload, $ = layui.jquery, element = layui.element;

        upload.render({
            accept : "file",
            elem : "#addFile",
            auto : false,   //关闭文件自动上传
            bindAction : "#upload", //文件上传触发按钮
            url : "upload",
            progress:function(value){//上传进度回调 value进度值
                element.progress('uploadProgressBar', value+'%')//设置页面进度条
            },
            before : function (obj) {
                /* var intId = setInterval(function () {
                     getUploadStatus(intId);
                 }, 1000); //每秒向服务端获取一次当前上传进度情况*/
                obj.preview(function (index,file,result) {
                    $('#demo1').attr('src',result);
                })
            },
            done : function (res, index, upload) {
                if(res.code != 200){
                    layer.open({
                        icon : 2,
                        skin : "layui-layer-molv",
                        content : res.msg
                    });
                }
                if (res.code<0){
                    layer.msg("上传失败")
                }
                layer.msg('上传成功')
            },
            error : function (res) {

            }
        });

    });
</script>
</html>

4.UserEntity(实体类)

package com.ljc.upload.entity;

import org.springframework.stereotype.Component;

@Component
public class UserEntity {
    private long readBytes =0L;
    private long allBytes=0L;
    private int currentIndex;

    public long getReadBytes() {
        return readBytes;
    }

    public void setReadBytes(long readBytes) {
        this.readBytes = readBytes;
    }

    public long getAllBytes() {
        return allBytes;
    }

    public void setAllBytes(long allBytes) {
        this.allBytes = allBytes;
    }

    public int getCurrentIndex() {
        return currentIndex;
    }

    public void setCurrentIndex(int currentIndex) {
        this.currentIndex = currentIndex;
    }

    @Override
    public String toString() {
        return "UserEntity{" +
                "readBytes=" + readBytes +
                ", allBytes=" + allBytes +
                ", currentIndex=" + currentIndex +
                '}';
    }
}


5.监听文件上传进程

package com.ljc.upload.listener;


import com.ljc.upload.entity.UserEntity;
import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

@Component
public class UploadProgressListener implements ProgressListener {
    private HttpSession session;

    public void  setSession(HttpSession session){
        this.session=session;
        UserEntity userEntity=new UserEntity();
        session.setAttribute("uploadStatus",userEntity);

    }


    @Override
    public void update(long readBytes,long allBytes,int index) {
        UserEntity userEntity=(UserEntity) session.getAttribute("uploadStatus");
        userEntity.setReadBytes(readBytes);
        userEntity.setAllBytes(allBytes);
        userEntity.setCurrentIndex(index);
    }
}

6.用于文件上传

import com.ljc.upload.listener.UploadProgressListener;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class LjcMultiparResolver extends CommonsMultipartResolver {
    @Autowired
    private UploadProgressListener progressListener;

    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = super.determineEncoding(request);
        progressListener.setSession(request.getSession());
        FileUpload fileUpload = prepareFileUpload(encoding);
        fileUpload.setProgressListener(progressListener);
        try {
            List<FileItem> fileItemList =  ((ServletFileUpload)fileUpload).parseRequest(request);
            return super.parseFileItems(fileItemList, encoding);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return null;
    }
}

7.controller


import com.ljc.upload.entity.UserEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadController {
    @RequestMapping("uploadPage")
    public String showUploadPage(){
        return "uploadPage";
    }

    @PostMapping("upload")
    @ResponseBody
    public Map<String, Object> upload(MultipartFile file){
        Map<String, Object> result = new HashMap<>();
        if (file != null && !file.isEmpty()){
                String filePath="g:/uploadFile/";
                File file1=new File(filePath);
                if (!file1.exists()){
                    file1.mkdirs();
                }
                String finalFilePath =filePath+file.getOriginalFilename().trim();
                File desFile=new File(finalFilePath);
                if (desFile.exists()){
                    desFile.delete();
                }
                try {
                    file.transferTo(desFile);
                    result.put("code", 200);
                    result.put("msg", "success");
                } catch (Exception e) {
                    result.put("code", -1);
                    result.put("msg", "文件上传出错,请重新上传!");
                    e.printStackTrace();
                }
        } else {
            result.put("code", -1);
            result.put("msg", "未获取到有效的文件信息,请重新上传!");
        }
        return result;
    }


    /**
     * 获取文件上传进度
     * @param request
     * @return
     */
    @RequestMapping("getUploadProgress")
    @ResponseBody
    public UserEntity getUploadProgress(HttpServletRequest request){
        return (UserEntity) request.getSession().getAttribute("uploadStatus");
    }

}

8.效果
springboot+layui实现文件上传(带进度条)_第2张图片

springboot+layui实现文件上传(带进度条)_第3张图片

多谢这位博主:文件上传

还有这位老哥的:文件上传实现并带有进度条

你可能感兴趣的:(springboot+layui实现文件上传(带进度条))