Home > Web Front-end > JS Tutorial > Basic use of file upload component WebUploader

Basic use of file upload component WebUploader

Guanhui
Release: 2020-05-08 09:43:11
forward
5808 people have browsed it

1. Origin

The company’s website community has a picture upload function. Since the website has been around for some years, the upload process was divided into categories based on whether the client supported flash or not. Two kinds of logic. If flash is supported, use the SWFuploader upload component to upload files. This has a better user experience. If flash is not supported, use ordinary input tags to upload. This method has incomplete functions and a poor experience. However, since the Chrome browser does not support flash by default, most of the time users use input tags to upload, and the upload experience is not good, so we decided to use Baidu's webuploader upload component to replace the original upload component. If you find some problems during the replacement process, record the areas that need attention.

2. Notes on using WebUploader

In fact, the general usage of third-party js plug-ins is similar. They basically import resource files, initialize plug-in objects according to configuration, and use objects. Methods or listening events complete specific functions, and webuploader is similar.

JS import resource file

<link href="../JS/webuploader/webuploader.css" rel="stylesheet" />
<script src="../JS/webuploader/jquery-1.12.4.min.js"></script>
<script src="../JS/webuploader/webuploader.js"></script>
Copy after login

You need to import the css file, jquery.js and webuploader.js files of wepuploader.

The css file is the style file of the upload button generated by webuploader for you. If you are not satisfied with the default style, first, you can modify the css yourself to meet your requirements. Another method is to prepare your own css file, then modify the source code of webuploader.js, and then specify the class of the button, mouseenter, mouseleave class, etc. The webuploader.js code location is as follows:

button.addClass(&#39;webuploader-pick&#39;);
                //button.addClass(&#39;btn&#39;);
                //button.addClass(&#39;btn-default&#39;);
    
                me.on( &#39;all&#39;, function( type ) {
                    var files;
    
                    switch ( type ) {
                        case &#39;mouseenter&#39;:
                            button.addClass(&#39;webuploader-pick-hover&#39;);
                            break;
    
                        case &#39;mouseleave&#39;:
                            button.removeClass(&#39;webuploader-pick-hover&#39;);
                            break;
    
                        case &#39;change&#39;:
                            files = me.exec(&#39;getFiles&#39;);
                            me.trigger( &#39;select&#39;, $.map( files, function( file ) {
                                file = new File( me.getRuid(), file );
    
                                // 记录来源。
                                file._refer = opts.container;
                                return file;
                            }), opts.container );
                            break;
                    }
                })
Copy after login

Since webuploader is based on jquery, jquery.js needs to be imported, and the jquery version must be greater than 1.10. The trick is that because the website is old, prototype.js was used to perform various operations before. In order to transfer $ usage rights to prototype, jQuery.noConflict() is also required. Of course, this operation is generally not needed.

The version of webuploader.js I use here is 0.1.2. I used 0.1.5 before. However, when performing flash upload in 0.1.5, if the server does not return a string in json format, the webuploader.js code will report an error and the client will not receive the return information. What our server returns is an ordinary string, so there is no other way but to use 0.1.2.

Initialize the webuploader object

Before initializing the object, because the upload button is generated by webuploader itself, first prepare the parent tag of the upload button, and webuploader will generate the upload tag within the tag. It can be div, span, etc. What I use is span:

<span id="uploadImage"></span>
Copy after login

Then I can initialize the webuploader object. The js code is as follows:

    var uploader = WebUploader.create({
        //是否允许重复的图片
        duplicate: true,
        auto: false, // 选完文件后,是否自动上传
        swf: &#39;../JS/webuploader/Uploader.swf&#39;, // swf文件路径
        server: "/upload.html", // 文件接收服务端
        pick: { id: "#uploadImage", innerHTML: "本地上传图片" }, // 选择文件的按钮。可选
        // 只允许选择图片文件。
        accept: {
            title: &#39;Images&#39;,
            extensions: &#39;gif,jpg,jpeg,bmp,png&#39;,
            mimeTypes: &#39;image/*&#39;
        },
        //线程数
        threads: 1,
        //单个文件大小限制
        fileSingleSizeLimit: 2000,
        //上传文件数量限制
        fileNumLimit:10,
        //上传前不压缩
        compress:false,
    });
Copy after login

The WebUploader.create() method generates the webuploader object (it seems that there are other methods to generate it, but This is not the point), just pass in the configuration object.

The server attribute specifies the server address for file upload.

The pick attribute specifies the upload button, and the id specifies which button through jquery's selector (it does not have to be the id selector of #)

The swf attribute specifies where to load the swf file when flash is enabled ( Webuploader is internally compatible with flash and h5, we don't need to pay attention to which method it uses)

auto After selecting the file, whether to automatically upload it, I don't use automatic upload here, because after selecting the file, I need to upload it on the UI Do a few things and then I'll manually specify to start uploading.

The configuration needs to pay attention to the above attributes. There are many other attributes, some of which have been commented in the above js. For others that are not included, you can refer to the official WebUploader documentation.

Listening to webuploader events

After configuring the above, you can see your upload button on the page, but the above is not the point. The key to using webuploader flexibly is to handle a series of events triggered by webuploader during the uploading of images. According to our business requirements, I mainly monitored the following events:

    //当有一批文件加载进队列时触发事件
    uploader.on("filesQueued", webFilesQueued);
    //当有一批文件加载进队列时触发事件
    //uploader.on("fileQueued", webFilesQueued);
    //单个文件开始上传
    uploader.on("uploadStart", uploadStart);
    //单个文件上传成功
    uploader.on("uploadSuccess", uploadSuccess);
    //单个文件上传过程中
    uploader.on("uploadProgress", uploadProgress);
    //所有文件上传结束
    uploader.on("uploadFinished", uploadComplete);
    //图片校验不通过时
    uploader.on("error", webFileQueueError);
    //上传出错时
    uploader.on("uploadError",webUploadError);
Copy after login

webuploader will select the file you select through the file dialog box The picture (can be one or multiple pictures) is added to a queue, and then all files in the queue are uploaded (note that if the thread you configure is greater than 1, webuploader supports multi-threaded upload).

filesQueued This event is triggered when a batch of files are loaded into the queue. At this time, the files have not yet started to be uploaded. You can perform some business logic. For example, I need to determine how many pictures have been uploaded this time, and then dynamically generate so many picture boxes on the page. After executing the business logic, I need to manually specify to start uploading (because I configured auto: false) and execute loader.startUpload() (if it is uploaded automatically, there is no need to manually execute this method), then all the pictures in the queue at this time will be The upload has started.

fileQueued is similar to filesQueued, but this is an event triggered when a single file is queued. This event will be triggered multiple times when multiple images are selected at one time.

uploadStart Event triggered when a single file starts to be uploaded.

uploadProgress is an event triggered during a single file upload. In the callback method, you can receive the percentage of upload. Using this percentage, we can dynamically display the upload progress bar.

uploadSuccess 单个文件上传成功触发的事件,在回调方法内你可以接收到服务器端返回的数据以及当前是哪个file对象上传成功,目测通过file对象可以获取到图片的缩略图对象(webuploader前端帮我们生成的),可以在UI上显示缩略图等等逻辑(根据自己的业务要求决定。。。。)。

function uploadSuccess(file, serverData) {
    doSomeThing();
}
Copy after login

uploadFinished 队列中所有文件上传成功时触发的事件,具体回调方法视业务逻辑决定。

error 图片在加入队列之前会进行校验,看大小、格式等等是否满足配置要求,校验不通过触发的事件,你可以在UI上弹窗提示用户

uploadError 这里图片校验通过,加入了队列,并且开始上传到服务器,如果服务器或者网络有问题导致出错触发的事件,可以提示用户上传不成功。

三、一些杂项

按照以上方法应该一般的上传问题都可以解决,不过这次替换过程中还遇到一些问题,记录如下:

上传总数量限制

在前端我们有总数量的限制,但是配置时fileNumLimit:10属性指的并不是总数量10张,而是该次对话框你选择的文件数量,如果文件对话框内你选了12张,那么webuploader也会上传10张,但是后面的两张会丢弃掉。如果想对总数量限制一种方法是修改webuploader.js的源码:

 uploader.on( &#39;beforeFileQueued&#39;, function( file ) {
                //实时获得上传限制的文件总数
                max = this.options.fileNumLimit;
                if ( count >= max && flag ) {
                    flag = false;
                    this.trigger( &#39;error&#39;, &#39;Q_EXCEED_NUM_LIMIT&#39;, max, file );
                    setTimeout(function() {
                        flag = true;
                    }, 1 );
                }
                return count >= max ? false : true;
            });
    
            uploader.on( &#39;fileQueued&#39;, function() {
                count++;
            });
    
            uploader.on( &#39;fileDequeued&#39;, function() {
                count--;
            });
    
            uploader.on( &#39;uploadFinished&#39;, function() {
                //count = 0; 限制总数量,而不是限制一次的文件数量
            });
Copy after login

数量校验结束后count会清0,把这个注释掉(上面js倒数第二行被注释的代码)那么fileNumLimit就是总数量了。

还有一种方法是webuploader会记录上传成功的文件数,自己拿到这个数来进行判断就行了。

chrome浏览器不能连续选择相同图片

连续上传同一图片时在chrome浏览器上总是不触发入队的事件,刚开始以为是配置的duplicate属性是false,后来发现duplicate属性是正确的true。这是chrome的特性,选择文件对话框关闭的时候会将input标签的value属性设置为这张图片的hash值?,如果input已经有了value属性(上一张图片的),并且和这一张的相同,那么将不触发change事件,也就是不上传了。解决方法:

function uploadComplete(file) {
        //解决chrome浏览器不能连续两次上传相同图片的bug k----------
        if ($("uploadImageDiv").select("input").length > 0) {
            $("uploadImageDiv").select("input")[0].value = "";
        }
        //解决chrome浏览器不能连续两次上传相同图片的bug k----------
}
Copy after login

监听上传完成事件,把input标签的value设为空就行了。

推荐教程:《JS教程

The above is the detailed content of Basic use of file upload component WebUploader. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jianshu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template