Web Uploader基本用法

来源:互联网 发布:抓包后怎么看mac地址 编辑:程序博客网 时间:2024/05/22 22:32

Web Uploader基本用法

  这一段时间在使用Web Uploader,所以记录下Web Uploader基本用法及多线程分片上传,片乱序问题。
  一、简单介绍
  WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。
  官网地址
  二、基本用法
  1、下载Web uploader,在html页面引入webuploader.js、webuploader.css、jquery-2.2.3.min.js。
  2、html页面很简单,thelist是文件信息列表,picker文件选择按钮,btnSync上传按钮

<div id="thelist" class="uploader-list"></div>    <div style="margin: 20px 20px 20px 0;">        <div id="picker" class="form-control-focus">选择文件</div>    </div>    <button id="btnSync" type="button" class="btnStyle">开始上传</button>

2、创建webuploader对象,并设置相关属性,绑定相关事件,具体参考官方API

<script>        var uploader = WebUploader.create({            // swf文件路径            //swf :'/webSocket/resources/swf/Uploader.swf',            // 文件接收服务端。            server : '/webSocket/server/upload',            //是否分片,true是            chunked : true,            //分片,每一片大小,不分片,此配置无效            chunkSize:16384,            //上传进程            threads : 100,            //表单数据            fromData : {                guid : 'guid'            },            // 选择文件的按钮。可选。            // 内部根据当前运行是创建,可能是input元素,也可能是flash.            pick : '#picker',            // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!            resize : false,        });        // 当有文件被添加进队列的时候        uploader.on('fileQueued', function(file) {            $("#thelist").append(                    '<div id="' + file.id + '" class="item">'                            + '<h4 class="info">' + file.name + '</h4>'                            + '<p class="state">等待上传...</p>'                            +'<div class='+'progressBar'                            +'><div class='+'barStyle'+'></div></div>'                            + '</div>');        });        uploader.on('uploadSuccess', function(file,response) {            $('#' + file.id).find('p.state').text("success="+response._raw);        });        uploader.on('uploadError', function(file,response) {            $('#' + file.id).find('p.state').text("error="+response);        });        uploader.on('uploadComplete', function(file) {            var fileBox = $('#'+file.id);            var stateBar = fileBox.find('.state');              $(stateBar).html("上传完成");            $('#' + file.id).find('.progress').fadeOut();        });        uploader.on('uploadStart', function(file) {            var fileBox = $('#'+file.id);            var stateBar = fileBox.find('.state');              $(stateBar).html("正在上传");        });        //进度条事件        uploader.on('uploadProgress',function( file, percentage){            var fileBox = $('#'+file.id);            var diyBar = fileBox.find('.progressBar');              var bar = diyBar.find('.barStyle');            //$(bar).html(":"+percentage.toFixed(2)*100+"%");            showDiyProgress( percentage.toFixed(2),10, file.id);        });

3、添加进度条方法

//操作进度条;        function showDiyProgress(percentage, speed, id) {            var progressBar=$("#" + id).find('.progressBar');            var proBarWith = parseInt(progressBar.width());            var bar = progressBar.find('.barStyle');            var startWidth = parseInt($(bar).width());            var endWidth = proBarWith * percentage;            var barWidth=0;            //初始化js进度条            //进度条的速度,越小越快            var speed = 1;            setInterval(function() {                //宽度要不能大于进度条的总宽度                if (barWidth <= endWidth) {                    while(barWidth <= endWidth){                        barWidth = barWidth + 1;                        $(bar).css("width", barWidth+"px");                    }                } else {                    //停止                    clearInterval(bar);                }            }, speed);        }

4、添加上传点击事件

$("#btnSync").on('click', function() {            if ($(this).hasClass('disabled')) {                return false;            }            uploader.options.formData.guid = Math.random();            uploader.upload();        });

5、接收端

public class WebUploadServer {    public void upload(@RequestParam(value = "file", required = false) MultipartFile file,     HttpServletRequest request,    HttpServletResponse response) throws JsonGenerationException,     JsonMappingException, IOException {        String guid=request.getParameter("guid");        //判断是否分片        if (request.getParameter("chunk") == null) {        //设置路径            String realPath             = request.getSession().getServletContext().getRealPath("/Upload/");    //获取文件名            String fileName = file.getOriginalFilename();            File targetFile = new File(realPath, fileName);            if (!targetFile.exists()) {                targetFile.mkdirs();            }            file.transferTo(targetFile); // 小文件,直接拷贝            response.getWriter().write("success");        } else {            int chunk = Integer.parseInt(request.getParameter("chunk")); // 当前分片            int chunks = Integer.parseInt(request.getParameter("chunks")); // 分片总计            String realPath = request.getSession().getServletContext().getRealPath("/Upload/");            String Ogfilename = file.getOriginalFilename();            File tempFile = new File(realPath, Ogfilename);            OutputStream outputStream = new FileOutputStream(tempFile, true);            InputStream inputStream = file.getInputStream();            byte buffer[] = new byte[1024];            int len = 0;            while ((len = inputStream.read(buffer)) > 0) {                outputStream.write(buffer, 0, len);            }            inputStream.close();            outputStream.close();            if(chunks-chunk==1)                response.getWriter().write("success");        }    }}


在上传文件的时候,遇到了文件名乱码或者文件乱码的情况,检查了jsp的页面一直都是utf-8,在服务端尝试了各种编码类型,发现都是错误的。最后发现是SpringMVC的配置文件没有显示配置文件上传的编码类型,所以导致编码不一致。

<bean id="multipartResolver"     class="org.springframework.web.multipart.commons.CommonsMultipartResolver"    p:defaultEncoding="UTF-8"    p:maxUploadSize="5400000"/>
0 0