springboot和jquery.form.js实现监听文件上传进度

说明

文件上传作为程序开发最常用的功能之一,上传进度展示也是必须的。但是有时候进度并不准,进度100%了实际上后台尚未接收完毕,本篇就介绍如何利用jquery的form插件来实时反馈文件上传进度。

实现效果

在这里插入图片描述
注意:最后100%停了一下才出现返回结果,因为服务器端在将二进制流写入到磁盘中耗费了点时间。

关于jquery.form

1.这个框架集合form提交、验证、上传的功能。
2.这个框架必须和jquery完整版结合,否则使用min则无效。
原理:利用js进行对form进行组装成ajax的url和data,原理还是用ajax来提交,其实这完全可以自己写,但是有这个框架可能会更简单。

  • 支持的功能有:
    -ajaxForm
    -ajaxSubmit
  • formToArray
  • formSerialize
  • fieldSerialize
  • fieldValue
  • clearForm
  • clearFields
  • resetForm

详细用法请参考:https://jquery.malsup.com/form/

开发步骤

1.文件上传类

@Controller
@RequestMapping("/api/file")
public class FileUploadController {
    
    
    @RequestMapping(value="/upload", method=RequestMethod.POST )
    @ResponseBody
    public Map<String,Object> uploadFile(@RequestParam("fileItem") MultipartFile fileItem )
    {
    
    

        String filename = fileItem.getOriginalFilename();
        try {
    
    
            byte[] fileBytes = fileItem.getBytes();
            Files.write(Paths.get("D:\\tmp\\" + fileItem.getOriginalFilename()), fileBytes);
        } catch (IOException e) {
    
    
            e.printStackTrace();

        }
        Map<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("message",filename+"上传成功!");

        return result;
    }
}

2.前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.13.0/themes/smoothness/jquery-ui.css">

    <!--<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>-->
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
    <script src="http:///code.jquery.com/ui/1.13.0/jquery-ui.js"></script>

    <style type="text/css">
        .progress{
      
      
            width: 500px;
            height:24px;
            line-height:24px;
        }
    </style>
</head>
<body>
    <h1>jquery.form方式展示文件上传进度</h1>
    <div id="progressbar" class="progress"></div>
    <div class="percent">0%</div >

    <div id="status"></div>
    <form action="/api/file/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="fileItem"><br>
        <input type="submit" value="Upload File to Server">
    </form>

    <script>
        $(function() {
      
      
            // 初始化进度条
            var progressbar = $( "#progressbar" );
            progressbar.progressbar({
      
      
                value: 0
                /*change: function() {
                    progressLabel.text( progressbar.progressbar( "value" ) + "%" );
                },
                complete: function() {
                    progressLabel.text( "上传完成!" );
                }*/
            });

            var percent = $('.percent');
            var status = $('#status');

            $('form').ajaxForm({
      
      
                beforeSend: function() {
      
      
                    status.empty();
                    var percentVal = '0%';
                    //bar.width(percentVal);
                    percent.html(percentVal);
                },
                uploadProgress: function(event, position, total, percentComplete) {
      
      
                    var percentVal = percentComplete + '%';
                    //bar.width(percentVal);
                    $( "#progressbar" ).progressbar({
      
      
                        value: percentComplete
                    });
                    progressbar.find( ".ui-progressbar-value" ).css({
      
      
                        "background": "rgb(105 167 69)"
                        //"background": '#' + Math.floor( Math.random() * 16777215 ).toString( 16 )
                    });
                    percent.html(percentVal);
                },
                complete: function(xhr) {
      
      
                    status.html(xhr.responseText);
                }
            });
        });
    </script>
</body>
</html>

3.修改application.yml

启动配置文件中添加以下内容,因为默认文件上传大小被限制在10m,此处放大到1G。

spring:
  servlet:
    multipart:
      max-file-size: 1000MB
      max-request-size: 1000MB

4.启动项目

访问:http://localhost:9000/ajaxupload.html
安图所示测试:
在这里插入图片描述

项目源码

觉得有帮助的朋友给老徐来个收藏+点赞+关注,:)

https://gitee.com/indexman/spring_boot_in_action/blob/master/websocket

Guess you like

Origin blog.csdn.net/IndexMan/article/details/121303341