使用uploadify插件的uploadifive上传对接fastdfs及文件回显,$('#file_upload').uploadifive异步请求以及参数的详细介绍

 

目录

效果图:

插件下载地址:

项目结构:

完整的yml配置:

pom

前端上传页面uploadify插件实现上传功能

controller层

返回的数据封装

uploadifive详细参数介绍


效果图:

 

插件下载地址:

Uploadify的js和css样式git下载地址:https://github.com/RonnieSan/uploadify

Uploadifys需要依赖于jq,所以在引入Uploadifys的js之前,需要先引入jq

 

项目结构:

 

springboot整合thymeleaf,如果读取css和js文件,需要在yml中加入以下配置:

spring:
  mvc:
    static-path-pattern: /static/**
  resources:
    static-locations: classpath:/static/

 

完整的yml配置:

server:
  port: 8081
spring:
  application:
    name: test-thymeleaf
  mvc:
    static-path-pattern: /static/**
  resources:
    static-locations: classpath:/static/
fdfs:
  so-timeout: 1500  #socket连接超时时长
  connect-timeout: 600  #连接tracker服务器超时时长
  resHost: 192.168.239.129  #文件服务器的ip
  storagePort: 80  #服务器nginx端口
  pool:
    jmx-enabled: true
  thumb-image:   #缩略图生成参数,可选
    width: 100
    height: 100
  tracker-list:  #TrackerList参数,支持多个,我这里只有一个,如果有多个在下方加- x.x.x.x:port
    - 192.168.239.129:22122

 

 

pom

<dependencies>
        <!--fastdfs-->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.2</version>
        </dependency>

        <!--模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--devtools热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
    </dependencies>

 

$('#file_upload').uploadifive方法参数介绍:

方法参数其实就是key-value结构, json字符串,ajax请求发送

  • file_upload:控件的id
  • ajax异步请求路径设置
  • 接口的参数名称
  • 回调函数,数据文件回显,以及设置一个占位槽,更新数据库值用

 

前端上传页面uploadify插件实现上传功能

uploadify.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>uploadify demo</title>
    <!--css-->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <link href="../static/css/uploadifive.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="container-fluid">
        <!--内容-->
        <div class="row">
            <div class="col-md-3">
            </div>
            <div class="col-md-2" style="float: left">
                <form >
                    <div class="form-group">
                        <label>File input</label>
                        <input type="file" id="file_upload" name="file">
                        <img src="#" id="show_img" style="width: 100px;height: 100px;display: none" >
                        <input type="hidden" id="hidden_img" name="prd_img" value="">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
            </div>
        </div>
    </div>

    <!--jq-->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!--bootstrap-->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="../static/js/jquery.uploadifive.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#file_upload').uploadifive({
                'uploadScript': 'file/upload',
                'fileObjName': 'file',
                'fileSizeLimit': 0,//上传文件的大小限制 0则表示无限制
                //在文件上传完成后触发  file.name:文件信息  data:返回的封装信息
                'onUploadComplete': function (file, data) {
                    if (data) {
                        //alert("返回的数据:"+data);
                        try {
                            var result = JSON.parse(data);
                            if (result.code === 200) {
                                var fullPath = result.data;
                                //回显
                                $("#show_img").attr("src",fullPath).show();
                                $("#hidden_img").val(fullPath);

                            } else {
                                alert("状态非200:"+result.message);
                            }
                        } catch (e) {
                            alert("报错:" + data);
                        }
                    }
                },
            })
        });

    </script>
</body>

</html>

 

 

controller层

UploadFileController改成上传到fastdfs服务器,同时返回封装类数据

@RestController
@RequestMapping("/file")
public class UploadFileController {
    @Autowired
    private FastDFSClientWrapper fdfs;

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        if (file==null){
            return ResultUtil.error("不能上传空文件");
        }
        try {
            String fullPath = fdfs.uploadFile(file);
            return ResultUtil.success(fullPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtil.error("上传文件失败");
    }

}

 

返回的数据封装

Result
package com.ldgroup.ldtest.thymeleafbootstrap.result;

/**
 * @Description
 * @Author by mocar小师兄
 * @Date 2020/4/14 21:40
 **/
public class Result {
    private Integer code;
    private String messsage;
    private String data;

    public Result(Integer code, String messsage) {
        this.code = code;
        this.messsage = messsage;
    }

    public Result(Integer code) {
        this.code = code;
    }

    public Result(Integer code, String messsage, String data) {
        this.code = code;
        this.messsage = messsage;
        this.data = data;
    }

   get,set省略
}

 

ResultUtil
/**
 * @Description
 * @Author by mocar小师兄
 * @Date 2020/4/14 21:40
 **/
public class ResultUtil {
    public static Result success(String data){
        return new Result(HttpStatus.OK.value(),null,data);
    }

    public static Result success(String data,String message){
        return new Result(HttpStatus.OK.value(),message,data);
    }

    public static Result error(String message){
        return new Result(HttpStatus.BAD_REQUEST.value(),message);
    }

    public static Result error(){
        return new Result(HttpStatus.BAD_REQUEST.value());
    }
}

 

 

包装fastdfs的上传、下载、删除代码在另一篇文章:

https://blog.csdn.net/Seven71111/article/details/105500224

 

 

uploadifive详细参数介绍

需要什么参数配置什么参数,如下

<script type="text/javascript">
            $(function() {
                $('#file_upload').uploadifive({
                    //传输设置-------------------------------------------------------
                    'uploadScript': '/Home/Upload',//定义服务器访问路径  (待改为webapi: /api/upload/file)
                    'fileObjName': 'fileData',//定义服务器接收参数名称
                    'method': 'post',//上传文件的提交方法,取值'post'或'get'
                    //'formData': { "imgType": "normal" }, //提交给服务器端的参数
                    //'checkScript': '/Home/Check',//检查目标文件夹中是否存在与上载文件同名的文件
                    'auto': false,//是否自动上传
                    'multi': true,//是否允许多文件上传

                    //样式-----------------------------------------------------------
                    'width': 120,//上传按钮的宽度(单位:像素)
                    'height': 30,//上传按钮的高度(单位:像素)
                    'buttonText': '请选择文件',//定义上传按钮显示的文字
                    'buttonClass': false,//要添加按钮的样式
                    'dnd': true, //是否允许拖放
                    'removeCompleted': false,//文件上传完毕后,是否从上传队列中移除
                    'queueID': false,//指定用于显示上传队列的父级元素id
                    'dropTarget': false,// Selector for the drop target

                    //文件约束--------------------------------------------------------------
                    'fileType': 'image/jpeg/jpg/png', //允许上传的文件类型。要允许所有设置为false,允许特定设置为['image/jpeg','video/*']
                    'truncateLength': 0,//指定文件名称的截取长度,设置该值后,文件名称超过该长度将会被截取
                    'fileSizeLimit': "10MB",//上传文件的大小限制 0则表示无限制
                    'uploadLimit': 9,//指定允许上传的最大文件数量
                    'simUploadLimit': 0, //一次可上传的文件数量
                    'queueSizeLimit': 9,// 指定上传队列中一次可容纳的最大文件数量(定义上传队列约束)
                    //'overrideEvents': [ 'onError'],//可指定多个插件默认事件中的事件名称,被指定的事件将不会执行

                    //事件监听-----------------------------------------------------------
                    //在uploadifive初始化结束时触发该事件
                    'onInit': function () {
                        alert('uploadifive初始化!');
                    },
                    //验证客户端浏览器兼容
                    'onFallback': function () {
                        alert('浏览器不支持HTML5,无法上传!');
                    },
                    //验证客户端文件是否已存在
                    'onCheck': function (file, exists) {
                        if (!exists) {
                            alert('文件名:'+ file.name + ' 不存在');
                        }
                    },
                    //验证客户端设定的约束
                    'onError': function (errorType, file) {
                        if (file != 0) {
                            $("#file_upload").uploadifive("debug"); //在控制台输出调试信息
                            var settings = $('#file_upload').data('uploadifive').settings;
                            switch (errorType) {
                                case 'UPLOAD_LIMIT_EXCEEDED':
                                    alert("上传的文件数量已经超出系统限制的" + settings.queueSizeLimit + "个文件!");
                                    break;
                                case 'FILE_SIZE_LIMIT_EXCEEDED':
                                    alert("文件 [" + file.name + "] 大小超出系统限制的" + $('#file_upload').uploadifive('settings', 'fileSizeLimit') + "大小!");
                                    break;
                                case 'QUEUE_LIMIT_EXCEEDED':
                                    alert("任务数量超出队列限制");
                                    break;
                                case 'FORBIDDEN_FILE_TYPE':
                                    alert("文件 [" + file.name + "] 类型不正确!");
                                    break;
                                case '404_FILE_NOT_FOUND':
                                    alert("文件未上传成功或服务器存放文件的文件夹不存在");
                                    break;
                            }
                        }
                    },
                    //在每添加一个文件至上传队列时触发该事件
                    'onSelect': function (queue) {
                        /*console.log("被取消的文件数量:" + queue.cancelled);
                        console.log("上传队列中的文件总数量:" + queue.count);
                        console.log("上传错误的文件数量:" + queue.errors);
                        console.log("被添加到上传队列中的文件数量:" + queue.queued);
                        console.log("被替换的文件数量:" + queue.replaced);
                        console.log("所选择的文件数量:" + queue.selected);*/
                    },
                    //当文件被放到该队列文件时触发该事件
                    'onDrop': function (file, fileDropCount) {

                    },
                    //上传进度更新时触发该事件
                    'onProgress': function (file, e) {
                        //if (e.lengthComputable) {//当文件上传长度可计算时
                        //    var percent = Math.round((e.loaded / e.total) * 100);//loaded:加载的btyes数 / total:要加载的总字节数
                        //}
                        //file.queueItem.find('.fileinfo').html(' - ' + percent + '%');
                        //file.queueItem.find('.progress-bar').css('width', percent + '%');
                    },
                    //在文件被添加到上传队列时触发
                    'onAddQueueItem':function(file) {
                        console.log('Test:' + file.type );
                    },
                    //在执行上传操作时触发(filesToUpload 需要上传的文件数)
                    'onUpload': function (filesToUpload) {
                        if (filesToUpload < 1) {
                            alert("未选择任何文件");
                            return false;
                        }
                    },
                    //在上传每一个文件时触发(file:正在上载的文件对象)
                    'onUploadFile': function (file) {},
                    //在文件上传完成后触发
                    'onUploadComplete': function (file, data) {
                        if (data) {
                            try {
                                data = JSON.parse(data);
                                if (data.result === true) {
                                    alert(file.name+"上传成功");
                                } else {
                                    alert(data.msg);
                                }
                            } catch (e) {
                                alert(data);
                            }
                        }
                    },
                    //队列中的所有文件被处理完成时触发该事件
                    'onQueueComplete': function (uploads) {
                        console.log("上传成功总文件数:" + uploads.successful);
                        console.log("上传失败总文件数:" + uploads.errors);
                        console.log("上传总文件数:" + uploads.count);
                        console.log("尝试的文件上载次数:" + uploads.attempts);
                    },
                    //在上传被取消时触发
                    'onCancel': function (file) {
                        console.log('Test:' + file.name );
                    },
                    //在清空队列时触发
                    'onClearQueue': function (queue) {
                        queue.css('border', '');
                    },
                    //在uploadifive销毁时触发该事件
                    'onDestroy': function () {}
                });
            });
        </script>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值